I am making an AJAX GET
request using jQuery to a PHP file. I want the PHP script to return a JSON object, however, currently it is returning a JSON string. I realise I can use JSON.parse
in the jQuery code, however, any experience I have in making an AJAX call to an API a JSON object is returned. I am trying to do the same with the php script however, it is returning a string as opposed to an object.
Does anyone know what the best practice is here, and if the best practise is to return a JSON object how I would do this using PHP?
Please see the code below:
js
$.get('test.php', function(data){
console.log((data));
});
php
<?php
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
3 Answers 3
In your PHP file, change the content type to application/json
.
JS
$.get('/process.php', function(data) {
console.log(data);
} );
PHP
<?php
header( "Content-type: application/json" );
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
Then your console should read Object {test: "true"}
rather than just the JSON string.
-
this is what I was looking foruser6002037– user60020372016年07月07日 11:06:20 +00:00Commented Jul 7, 2016 at 11:06
Add json to the end of your get function to return json
$.get('test.php', function(data){
console.log((data));
},'json');//here
and/or add this header in php
header('Content-Type: application/json');
more info here
-
get, getjson, ajax same thingmadalinivascu– madalinivascu2016年07月07日 11:04:55 +00:00Commented Jul 7, 2016 at 11:04
-
@madalinivascu no not same thing.Jai– Jai2016年07月07日 11:05:21 +00:00Commented Jul 7, 2016 at 11:05
-
this is what I was looking for, however, i didn't have to add
'json
' to the get requestuser6002037– user60020372016年07月07日 11:06:59 +00:00Commented Jul 7, 2016 at 11:06 -
the json at the end ensures that the data received is parsed as jsonmadalinivascu– madalinivascu2016年07月07日 11:14:41 +00:00Commented Jul 7, 2016 at 11:14
-
@madalinivascu jQuery tries to automatically guess it.gcampbell– gcampbell2016年07月07日 11:23:24 +00:00Commented Jul 7, 2016 at 11:23
Without modifying PHP script you can do:
$.get( "test.php", function( data ) {
var arr = $.parseJSON(data);
console.log(arr);
alert(arr.test);
});
-
Although technically you can just parse the json (you can use JSON.parse() which is native to JavaScript instead of going through the jQuery library to do so), sending text based responses that are meant to be JSON responses is not a good idea and can lead to mismatching data and unexpected results. -1.Marcus Parsons– Marcus Parsons2020年05月12日 01:47:32 +00:00Commented May 12, 2020 at 1:47
JSON.parse
? There's probably some jQuery method that parses the response automatically, which might be what you're thinking about.JSON.parse
but i just want to know if i can do this server side so that the correct format is received in the browser. does this make sense?JSON.parse
for you. Anyway, it works now.