Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get associative array after post via ajax

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$_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 ?

>Solution :

The issue is because the string is formData becomes double-wrapped, ie. a string of key/value pairs within a string of key/value pairs. As only 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading