I want to pass the key values into php page.
At php page, I will start to read value by matching ajaxcallid
.
But it not working.
It gotta do with syntax/way I am passing in causing error.
parse error
invalid json: ajax call id is missing
JavaScript/AJAX:
var person = {
"Address" : "123 Anywhere St.",
"City" : "Springfield",
"PostalCode" : 99999
};
alert(person);
person= JSON.stringify(person);
alert(person);
$.ajax({
url: 'ROOT_URL/admin/ajaxtest.php',
type: "POST",
dataType: 'json',
data: {ajaxcallid: '26', jsarr: person},
timeout: 5000,
success: function(output) {
alert(output.Address);
},
});
PHP:
<?php
if (isset($_REQUEST['ajaxcallid']))
{
if($_REQUEST['ajaxcallid']==26)
{
//example, I want to read value of person.Address, person.City,
//person.PostalCode
//what is the easiest way
$phparr= json_decode($_REQUEST['jsarr']);
//do all other operation
$output= json_encode($phparr);
}
}
else
{
$output= "ajax call id is missing";
}
echo $output;
?>
json_encode() is a native PHP function that allows you to convert PHP data into the JSON format. json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] ) : string. The function takes in a PHP object ($value) and returns a JSON string (or False if the operation fails).
Parsing JSON with PHPPHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.
To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.
Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.
If you are not using dataType : 'json', you might need to do stripslashes
$.post(window.data.baseUrl, {posts : JSON.stringify(posts)});
And in php:
$posts = json_decode(stripslashes($_POST['posts']));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With