Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json stringify to php

Tags:

json

jquery

php

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;
?>
like image 612
i need help Avatar asked Feb 14 '11 05:02

i need help


People also ask

What is JSON Stringify PHP?

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).

Can we use JSON parse in PHP?

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.

How can I get JSON encoded data in PHP?

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.

Can I JSON Stringify a 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.


1 Answers

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']));
like image 193
Evalds Urtans Avatar answered Nov 15 '22 04:11

Evalds Urtans