Friday, April 17, 2009

CODE: JSON from JS > PHP

JSON from JS to PHP was much more easier or maybe difficult if you don't know how to use AJAX again I recommend using prototype as it's simplify ajax method a lot. You can get the code in www.prototypejs.org

jsfile.js

to preapare a json variable that compatible with php we use prototype's $H method add a slashes in every quote and then format to json with "toJSON()" function ( You might think of using slashes when passing variable from php to js using addslashes method, trust me it's not working. But correct me if you found another solution ).

function send_json_to_php() {
var preparejson = $H({name:'Violetx', occupation:'characterx', age:30 });
var json = preparejson.toJSON();

//below is an ajax function -- prototype way
new Ajax.Request('php_accept_json.php',{
parameters: 'json='+json
});
}

php_accept_json.php

$json = $_POST['json'];
$decode = json_decode(stripslashes($json));
print_r($json);

*Don't forget you need to stripslashes first before do json_decode

//you will get below result
stdClass Object
(
[name] => Violetx
[occupation] => characterx
[age] => 30
)

which you can access each value like this $json->name, $json->age, etc.

Easy ? yep , this is only small thing but it will greatly help programmer. From CODE: JSON from PHP > JS article you remember we send a PHP json variable to javascript. you can pass that variable directly using ajax back to PHP and php still can read it using the same method in php_accecpt_json.php.

You can imagine the advantage yourself


----------END----------

0 comments:

Post a Comment