I want to pass an array from Jquery to PHP.
My jquery:
var jsonFormat = JSON.stringify(myArray);
$.post("myPHPFile.php", jsonFormat).done(function(data) {
$('.foo').append(data);
});
I see myArray in the browser console as expected
My PHP:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS');
//echo json_decode(array('success' => 'yes'));
if ($_SERVER['REQUEST_METHOD']=="POST"){
$jsonFormat = $_POST['jsonFormat'];
echo $jsonFormat;
}
?>
In the browser console I get status 200 ok, but no response. I am expecting to see the array as a response.
You have passed PHP a request with a JSON body, but you are trying to treat it as application/x-www-form-urlencoded
data, not application/json
data.
Use $.post("myPHPFile.php", { myData: myArray })
and $_POST['myData']
instead. jQuery will encode the data as application/x-www-form-urlencoded
then (it will even default to using PHP's unusual naming conventions).
I would do something similar to this:
Jquery
$.post("myPHPFile.php", myArray.serialize(), function(data) {
$(".foo").append(data);
}, "json");
myArray.serialize() turns your array into a string that will be posted to your PHP file like this: var1=text&var2=text
PHP
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
// repeat for each variable being posted.
// your php code that does whatever it will do with the variables.
// data to return to Jquery will be put back into an array like this:
$return['var3'] = $var3;
$return['var4'] = $var4;
echo json_encode($return);
unset($_POST);
?>
The data returned is datatype = json which can be accessed in your Jquery code like this: data.var3 data.var4
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.