phantom phantom - 1 year ago 67
Ajax Question

Return JSON object from php script

I am making an AJAX

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
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:


$.get('test.php', function(data){



$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);

Answer Source

In your PHP file, change the content type to application/json.


$.get('/process.php', function(data) {      
} );



    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.