I’m seeing some peculiar behavior with sending a JSON string back from PHP to Jquery’s $.ajax function.
when I visit my php script from a browser or from calling it via command line with php, it returns completely valid JSON (tested with jsonlint.com). However, when I make an AJAX call from my HTML file I always get NULL back.
Basically from PHP I’m doing this:
// case in a switch that handles command 'getinfo':
$url = "http://someapi.com:1234/api/entity/" . $tagid;
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_USERPWD, "user:pass" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
$reply = curl_exec( $ch );
header('Content-Type: application/json');
echo $reply;
This spits out this:
[ {
"class" : "entity",
"guid" : "IT_EQUIPMENT_abcdef12345677890",
"retired" : false,
"deletable" : true,
"$aAssetTamper" : false
} ]
I’ve tried both with and without RETURNTRANSFER set, and also with and without the header() line. On the HTML side, I am calling with Ajax:
$.ajax({
url: "gimmedata.php",
dataType: "json",
cache: false,
async: false,
data: { 'cmd' : 'getinfo', 'tagid' : $('#tag').val },
success: function( data, textStatus ) {
// rfcode location
console.log(data);
}
});
The status always returns “success”, and the data is always “[]”.
Weird thing is, if I copy the output from the PHP script and then paste it back into the script itself, then echo that string without going through curl, then my AJAX call works fine:
echo '
[ {
"class" : "entity"
"guid" : "IT_EQUIPMENT_abcdef12345677890",
"retired" : false,
"deletable" : true,
"$aAssetTamper" : false
} ]';
return;
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_USERPWD, "user:pass" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
$reply = curl_exec( $ch );
header('Content-Type: application/json');
echo $reply;
I have no idea what it can be. Any clue? Is curl_exec doing weird things to the text?
Your data passing from JavaScript is wrong:
You should use
.valas a function, not as a property: