Skip to content Skip to sidebar Skip to footer

Send Json Data To Server Jquery.ajax

Another json related question unfortunately... Consider the following json [{'details':{ 'forename':'Barack', 'surname':'Obama', 'company':'government', 'email':'bigcheese@whitehou

Solution 1:

You have to have a key/value pair to receive the data in php with $_POST[key]. Sending the array you have all by itself is not best approach since you already have structure to object

I would unwrap the outer array, since you are only sending one object inside it

Then Object would look like

{"details":{
"forename":"Barack",
"surname":"Obama",
"company":"government",
"email":"bigcheese@whitehouse.com",
"files": [{
      "title":"file1","url":"somefile.pdf"
       },
       {
       "title":"file2",
       "url":"somefile.pdf"
       }]
}
}

In php would receive with $_POST['details']. Don't convert to JSON, just pass the whole object to $.ajax data property.

If you get parserror from ajax, is on receiving side and sounds like either getting a 500 eror from php or not sending back json as expected by your dataType

Solution 2:

First, the original JSON string is of wrong format. Try

{
  "details":{
    "forename":"Barack",
    "surname":"Obama",
    "company":"government",
    "email":"bigcheese@whitehouse.com",
    "files": [
      { "title":"file1","url":"somefile.pdf" },
      { "title":"file2","url":"somefile.pdf"}
    ]
  }
}

Second, the data sent to PHP has already parsed into an array, but not in JSON. To echo, you must use json_encode to convert the array back to JSON string

echo json_encode($_POST);
exit;

Solution 3:

Since you are not passing the JSON as a field, you can do:

<?php$post = file_get_contents("php://input");
  $json = json_decode($post);
  var_dump($json); // Should be a nice object for you.

Post a Comment for "Send Json Data To Server Jquery.ajax"