简体   繁体   中英

Wordpress - Posting Json encoded Array to PHP returns nothing/NULL

I have several Inputs on my Plugins site. I gather the values of those and push them into an array. Then use the jQuery.post method to Post it to my PHP script.

Javascript:

var json = JSON.stringify(output); // output is an array with multiple strings
var data = {
    "action" : "add",
    "output" : json,
}
jQuery.post(ajaxurl, data, function(response){
    console.log(response); // logs the response from PHP
})

PHP:

$array = json_decode($_POST['output']);
update_option("option", $array);
var_dump($array); // returns NULL in console
echo $array; // returns nothing in console
wp_die();

I want PHP to return the array to JS and save it as the option.

This is my first Question here. Please feel free to give me tips on how to improve my question and code.

Solution

It seemed to have problems with the '\\' in the JSON String that was posted.

$array = json_decode(stripslashes($_POST['output'])) did the job

If you want the script to return the same object as it got:

// The second param "true" makes sure we get an associative array
// instead of an object.
$array = json_decode($_POST['output'], true);
update_option("option", $array);

// Set the correct content header (good practice)
header('Content-Type: application/json');

// Echo the string representation of the json-object
// Let's use the same as we got in the $_POST['output']
echo $_POST['output'];

wp_die();

Found a solution. It is written in the question under "solution"

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