Search code examples
jqueryajaxserializationstringify

mixing stringify and serializeArray in one jQuery ajax request


I am trying to use jQuery to send an ajax request that has normal form data that has been serialized. I also need to send a stringified array of data along with the serialized data. My question is how to I combine the two when I make the ajax request.

Currently, with the script below I can send the jsonString variable over and pick it up in PHP with $_POST['data']; How do I tack on the formData variable to that so I can pick up each form element in a PHP POST?

var jsonString = JSON.stringify(selection);  //selection is an array of values
var formData = JSON.stringify($("#formFields").serializeArray());
    $.ajax({
        type: "POST",
        url: "processor.php",
        data: {data : jsonString},
      //data: {data : jsonString, formData},  was thinking this but does not work
        cache: false,

        success: function(data){
            console.log(data);
        }
    });

Solution

  • What about this?

    var selection = [];
    selection[0] = "property_value";
    var jsonString = JSON.stringify(selection);  //selection is an array of values
    var formArray = $("#formFields").serializeArray();
    formArray.push({name: 'selection', value: jsonString});
    var formData = JSON.stringify(formArray);
    alert (formData);