I have not worked with json yet. and have no idea how it works I want to use jquery for performing ajax with php file. is it advisable to use json here. heard from someone that json is light weight. Is that true? if yes how would i use json for ajax-php peration with jquery
2 Answers
JSON is an information interchange format based on JavaScript literal notation (but is actually a subset of literal notation, you may only use strings, numbers, objects, booleans and arrays, from memory).
Unless you need to receive data back, you won't use it. It is lightweight compared to something like XML.
If you need to get JSON using jQuery, you can use the high level AJAX API call called getJSON() which is as simple as....
jQuery
$.getJSON('path/to/whatever.php', function(obj) {
alert(obj.name);
});
PHP
header('Content-Type: application/json');
echo json_encode(array('name' => 'bob'));
If you wanted to throw away requests that don't look like AJAX, use this...
if (isset($_SERVER['X-REQUESTED-WITH']) AND $_SERVER['X-REQUESTED-WITH'] !== 'XMLHttpRequest') {
die('XHR only.');
}
6 Comments
Parag
huhmmm... ok will give a try to jason with jquery and see.. thanks
Parag
This json code is not working . any idea why so?? $.getJSON('fruitvarities.php', {fruitName:1}, function(data){ $('#testarea').html(data); });
Parag
and this is my php file <?php header('Content-Type: application/json'); echo "Here is my sample text.to check if json is working"; ?>
alex
@Parag
fruitvarities.php isn't returning JSON, just a string.Parag
huh...!!! i actually wanted to grab some data from database(ex property listings) format it in table format and put them up using ajax json, php. its not possible with json?
|