简体   繁体   中英

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@whitehouse.com",
"files": [{
      "title":"file1","url":"somefile.pdf"
       },
       {
       "title":"file2",
       "url":"somefile.pdf"
       }]
}
}]

I need to send this data to a php script on my server and then interact with it on the server but don't know how.

I'm sending it via jquery.ajax and its being sent fine (no error messages) and heres the code. (newJson is my json object I've created exactly as above)

$.ajax({
type: "POST",
url: "test.php",
dataType: 'json',
data: newJson,
success: function(msg) 
    {
    alert(msg);
    },
error: function(jqXHR, textStatus) 
    {
    alert(textStatus);
    }
});

So in my php script so far I just want to echo back the content as a string which displays in the success alert

<?php
header('Access-Control-Allow-Origin: *'); 
echo $_POST;
?>

but that just gives me a parse error.. so any ideas you wonderful people?

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

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM