Home > front end >  Get associative array after post via ajax
Get associative array after post via ajax

Time:05-06

I need to send a form and a array/string to the server.

My Ajax looks like this:

 var formData = $("#formpv").serialize();
        $.ajax({    
            type: 'POST',
            url: 'scripts/formIntoDB.php',
            data: formData,

In this way I can retrieve the form data in PHP like this:

$_POST['name'];
//Output "Foobar"

But when I send the the serialized formdata and another param like this:

 var formData = $("#formpv").serialize();
 var posData = "TEST";

        $.ajax({    
            type: 'POST',
            url: 'scripts/formIntoDB.php',
            data: {form: formData, pos: posData},

And try to get name now in PHP:

$_POST['form']['name'];

This just throws PHP Parse error: syntax error, unexpected '['

Whats the difference when I send the data like this data: {form: formData, pos: posData} and data: formData ?

CodePudding user response:

The issue is because the string in formData becomes double-wrapped, ie. a string of key/value pairs within a string of key/value pairs. As only the top level of this is deserialised, your PHP code cannot read the second level in the manner you intend.

To fix this you either need to manually create the entire object, eg:

$.ajax({    
  type: 'POST',
  url: 'scripts/formIntoDB.php',
  data: {
    form: {
      name: $('#yourNameInput').val(),
      // all your other inputs here...
    }, 
    pos: posData
  }
});

Or you instead could keep the request data flat and just add pos using a hidden input within the form.

  • Related