locked
'serialize' WITHOUT some form elements RRS feed

  • Question

  • User-1641868886 posted

    Hi,

    I have a form to submit via a JQuery function. Here is the function:

    function SubmitForm(form) {
                $.validator.unobtrusive.parse(form);
                var Prov_Id = $("#Prov_Id :selected").val()
                if ($(form).valid()) {
                    $.ajax({
                        type: "POST",
                        url: form.action,
                        data: $(form).serialize(),
                        success: function (data) {
                            if (data.success) {
                                Popup.dialog('close');
                                dataTable.ajax.reload();
                                $.notify(data.message, {
                                    globalPosition: "top center",
                                    className: "success"
                                })
    
                            }
                        }
    
                    });
                }
                return false;
            }

    My issue is that on clicking "Submit" the form hangs up on the "Prov_Id" parameter. I think I know why, but not what to do about it. 

    The "Prov_Id" parameter is the third dropdownlist in a 3 part cascading ddl. I do not want to include the first two, "State" and "City" in the 'serialize' action

    I do not know how to '.serialize' the form while excluding those two form elements. If there is a way, plz advise, or point me to an example. Thanks much.

    Tuesday, February 5, 2019 11:06 PM

Answers

  • User-474980206 posted

    you did the attribute remove wrong. you need to remove the name attribute:

              $("#State").removeAttr("name");
                $("#City").removeAttr("name");     

    as this may break validation, so I'd remove before validation parse().  or remove, serialize, then add back. do this after .valid() and before ajax call:

    $("#State").removeAttr("name");
    $("#City").removeAttr("name");     
    
    var data = $(form).serialize();
    
    $("#State").attr("name","State"); 
    $("#City").attr("name","City"); 
    

    though I'd just filter the form data 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, February 11, 2019 11:45 PM

All replies

  • User-474980206 posted

    pretty simple. use serialize array and filter

     data: $(form).serializeArray().filter(function(r) { 
                return ["name1","name2"].indexOf(r.name) < 0
             }),

    Wednesday, February 6, 2019 2:15 AM
  • User-1174608757 posted

    Hi ReidMelSam,

    According to your description, I suggest remove the attribute 'name' of "State" and "City"  before serialize() the form, then you could get  the value you want. Here is the demo , I hope it could help you.

    <head runat="server">
        <title></title>
        <script src="../Scripts/jquery-3.3.1.js"></script>
        <script>
           $(function() {
    
               $("#but").click(function () {
                   $("#a1").removeAttr("name");
                     $("#a2").removeAttr("name");
                   alert($("#main").serialize());
    
      });
    
    });
        </script>
        
    </head>
    <body>
        <form id="main">
       <select id="a1" name="a1">
      <option value="1">Category 1</option>
      <option value="2">Category 2</option>
    </select>
             <select id="a2" name="a2">
      <option value="1">Category 1</option>
      <option value="2">Category 2</option>
    </select>
             <select id="a3" name="a3">
      <option value="1">Category 1</option>
      <option value="2">Category 2</option>
    </select>
           

    You could see as below:

    Best Regards

    Wei Zhang

    Wednesday, February 6, 2019 5:21 AM
  • User-1641868886 posted

    Okay I think I'm getting close. I used Wei Zhang (2nd method) suggestion on "removeAttr" as it seemed a slimmer solution. I want to make sure I did not place it in the wrong position:

    function SubmitForm(form) {
               
                $.validator.unobtrusive.parse(form);
                $("#State").removeAttr("State");
                $("#City").removeAttr("City");           
                var Prov_Id = $("#Prov_Id :selected").val()
                if ($(form).valid()) {
                    
                    $.ajax({
                        type: "POST",
                        url: form.action,
                        data: $(form).serialize(),
                        success: function (data) {
                            debugger;
                            if (data.success) {
                                Popup.dialog('close');
                                dataTable.ajax.reload();
                                $.notify(data.message, {
                                    globalPosition: "top center",
                                    className: "success"
                                })
    
                            }
                        }
    
                    });
                }
                return false;
            }

    Now I am getting a warning:  Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/  

    ...and the code breaks as soon as I hit the "Submit" button, so I do not have a chance to step through my code on the page (JQuery/javascript) or in my controller action. I am curious if 1) the "removeAttr" commands are in the wrong place; or 2) if my javascript for the "City(string State)" and "Provider(string City)" dropdownlists might be causing the break. All the javascript for the modal popup and its "submit" are on the dataTable "Index" page, but the javascript for the two ddls is on the partialView page for the popup "AddorEdit" view. I'm wondering if the j-script for the two ddls has to be moved to the same location as where the modal popup is being scripted. Once the modal is loaded, the three ddls all populate as expected.

    Plz advise if I need to show these.

    Thx again,

    RC

     

    Monday, February 11, 2019 11:30 PM
  • User-474980206 posted

    you did the attribute remove wrong. you need to remove the name attribute:

              $("#State").removeAttr("name");
                $("#City").removeAttr("name");     

    as this may break validation, so I'd remove before validation parse().  or remove, serialize, then add back. do this after .valid() and before ajax call:

    $("#State").removeAttr("name");
    $("#City").removeAttr("name");     
    
    var data = $(form).serialize();
    
    $("#State").attr("name","State"); 
    $("#City").attr("name","City"); 
    

    though I'd just filter the form data 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, February 11, 2019 11:45 PM
  • User-1641868886 posted

    Thanks for staying up on this, Bruce. I took your suggestion...changed the script to array/filter:

    data: $(form).serializeArray().filter(function (r) {
                            return ["UserName", "Code", "Prov_Id", "ProviderName", "DateOfPurch", "Charge", "NetCharge"].indexOf(r.name) < 0
                        }),

    ...this serializes from the above elements, omitting the "State" and "City" ddl elements, retaining only the third of three ddl elements, which is "Prov_Id". Here are a couple of observations:

    1) the form is in a modal/popup called by a "PopupForm" script on the "Index" view. When I employ ONLY the "Prov_Id" dropdownlist (no "State" or "City"), the form operates as expected, writes a new row to the database table, which appears on refresh of the dataTable (the "Index" view).

    2) when I add the "State" and "City" dropdownlists, I am also adding scripts to a) get selected "State" to populate the "City" list, and b) get selected "City" to populate the "Prov_Id" dropdownlist.

    These scripts are on the "AddorEdit" view, not on the "Index" view that calls the popup (don't know if that matters or not). Here they are:

    $(document).ready(function () {
            $("#State").change(function () {
                var StateSymb = $(this).val();
                //debugger
                $.ajax({
                    type: "post",
                    url: "/GrocBills/GetCities",
                    data: { State: StateSymb },
                    dataType: "json",
                    success: function (response) {
                        $("#City").empty();
                        $("#City").append(response.map(function (r) {
                            return $('<option>').text(r.City)[0];
                        }));
                    }
                });
            })
    
            $("#City").change(function () {
                var CityName = $(this).val();
                //debugger
                $.ajax({
                    type: "post",
                    url: "/GrocBills/GetProviders",
                    data: { City: CityName },
                    dataType: "json",
                    success: function (response) {
                        $("#Prov_Id").empty();
                        $("#Prov_Id").append(response.map(function (r) {
                            return $('<option>').text(r.ProviderName)[0];
                        }));
                    }
                });
            })
        });

    I am trying to figure out if:

    1) I am failing to capture the "Prov_Id" in the second function. I am populating on "Prov_Id" but I am changing to "text(r.ProviderName)" to show the names rather than the Ids in the dropdownlist. Am I populating this dropdownlist with ONLY the "ProviderName" and my controller action is left with no "Prov_Id"? (a gap in my knowledge is over how the script and the controller action and model methods interact...my method DOES call for "Prov_Id" as val and "ProviderName" as text).

    2) I have a script conflict as to where the scripts reside for the dropdowns (on "AddorEdit") vs the SubmitForm (on the "Index") and if that is what is still giving me the error:

    [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated -  jquery-3.3.1.min.js:formatted:3828

    ...and when I click on the jquery link, the line for the error reads:

    'if (s.open(t.type, t.url, t.async, t.username, t.password),'     **this is the red underlined error**

    Finally, did I construct the "serializeArray" as I should, keeping all the elements except the "State" and "City"?

    Thanks again.

    RC

    Tuesday, February 12, 2019 5:17 PM
  • User-1641868886 posted

    Okay Bruce, disregard almost ALL of the previous post. I figured out why I am hanging up on "Prov_Id" dropdownlist. In the second dropdownlist function shown below, I DID have an issue capturing the val of "Prov_Id" in my "append" function. I made the following change:

    $("#Prov_Id").append(response.map(function (r) {
                            return $('<option>').text(r.ProviderName).val(r.Prov_Id)[0];

    ...so it was appending with the "text(r.ProviderName)" but not the "val(r.Prov_Id)" and that was failing to load the dropdown list with the needed value/name pair. I took a guess on that, and the syntax for adding it. Lucked out!

    Thanks again for all your help!

    RC

    Tuesday, February 12, 2019 6:42 PM