PHP : JSON
Encode
Turn a php array into a JSON string.
$assoc = array('a' => 1, 'b' => 2, 'c' => 3);
echo json_encode($assoc);
// '{"a":1,"b":2,"c":3}'
$array = array('a', 'b', 'c');
echo json_encode($array);
// '["a","b","c"]'
$array = array('a', 'b', 'c');
echo json_encode($array, JSON_FORCE_OBJECT);
// '{"0":"a","1":"b","2":"c"}'
Decode
Turn a JSON string into a native php array.
JSON Array
$json = '["apple","orange","banana","strawberry"]';
$ar = json_decode($json);
echo $ar[0]; // apple
JSON Object
$json = '{
"title": "JavaScript: The Definitive Guide",
"author": "David Flanagan"
}';
$book = json_decode($json);
echo $book->title; // JavaScript: The Definitive Guide
//or
$book = json_decode($json, true);
echo $book['title']; // JavaScript: The Definitive Guide
JSON Complex Data
$json = '[
{
"title": "Professional JavaScript",
"author": "Nicholas C. Zakas"
},
{
"title": "JavaScript: The Definitive Guide",
"author": "David Flanagan"
}
]';
$books = json_decode($json);
echo $books[1]->title; // JavaScript: The Definitive Guide
//or
$books = json_decode($json, true);
echo $books[1]['title']; // JavaScript: The Definitive Guide
More Info: http://www.dyn-web.com/tutorials/php-js/json/decode.php
Detect if AJAX Request
function is_ajax_request() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
}
if(is_ajax_request()) {
echo "Ajax response";
} else {
echo "Not ajax";
}