user6002037
user6002037

Reputation:

Return JSON object from php script

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);

Upvotes: 7

Views: 13131

Answers (3)

Pandicted
Pandicted

Reputation: 31

Without modifying PHP script you can do:

$.get( "test.php", function( data ) {
 var arr = $.parseJSON(data);
 console.log(arr);
 alert(arr.test);
});

Upvotes: 0

madalinivascu
madalinivascu

Reputation: 32354

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

Upvotes: 2

Myke Meynell
Myke Meynell

Reputation: 191

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.

Upvotes: 13

Related Questions