Sending multiple forms data through jQuery Ajax

前端 未结 2 787
失恋的感觉
失恋的感觉 2021-02-03 11:04

I have two forms for which I want to send the data through jQuery Ajax call. I managed to send it successfully for one form but I am not able to send the data from both of them

相关标签:
2条回答
  • 2021-02-03 11:56

    You're using a function call in your filtergroup2 form that doesn't exist.

    filterBy2() I assume needs to be filterBy()

    0 讨论(0)
  • 2021-02-03 12:02

    jQuery's serialize() method concatenates your input values with an '&' symbol - therefore when you are pushing two serialized form data, you are creating an array and not concatenating the values in two forms with '&' (which is the one that will be parsed correctly). You can either: (1) concatenate the items in the array into a string with '&' or (2) use $("#form1, #form2").serialize() to do it:

    function filterBy() { 
        // Construct data string
        var dataString = $("#filter-group1, #filter-group2").serialize();
    
        // Log in console so you can see the final serialized data sent to AJAX
        console.log(dataString);
    
        // Do AJAX
        $.ajax( {
            type: 'POST',
            url: 'filter.php',
            data: dataString,
            success: function(data) {
                console.log(data);
                $('#message').html(data);
            }
        });
    }
    

    [Edit]: On a side note, I highly discourage using inline JavaScript. You should separate content from function. Instead, use the .click() function, like:

    $("form input[type='checkbox']").click(function() {
        var dataString = $("#filter-group1, #filter-group2").serialize();
        // (and more...)
    });
    

    I also don't exactly understand the reasoning behind using two separate forms...

    0 讨论(0)
提交回复
热议问题