Reputation: 5
What I'm doing is returning an RSS feed obtained via a PHP cURL. I return $returnedData which is an associative array that looks something like this:
array(2){
["lastupdate"] => string(29) "Tue, 11 Feb 2014 15:25:42 GMT"
["feed"] => array(20) {
<items contained within ["feed"][0] to ["feed"][19] (very large)>
}
}
I tried to run a json_encode before returning it to Ajax, but all it essentially did was convert my array into one large string. My Ajax is as follows:
$.ajaxSetup ({
cache: false
});
request = $.ajax ({
type: "GET",
url: "dataFetcher.php",
data: arg,
});
request.done(function(response){
var resultsArray = response;
$("#message").text(resultsArray);
});
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
The thing is, I don't exactly know what I'm getting. If I do var_dump($returnedData) instead of return $returnedData I know that I get a string. But if I simply return $returnedData, I can't tell what Ajax is receiving. I tried changing the text displayed by using resultsArray[0] or resultsArray[1] or resultsArray["lastupdate"] hoping that it worked, but it didn't.
Would really appreciate it if someone could shed some light on what I'm not doing/what I'm doing wrong here.
Thanks!
Upvotes: 0
Views: 63
Reputation: 8301
Two things:
json_encode
in your PHP script to encode the data.So:
request = $.ajax ({
type: "GET",
url: "dataFetcher.php",
data: arg,
dataType: 'json' // <--- Your response parameter will be in JSON format by default, now.
});
Upvotes: 1
Reputation: 38345
AJAX receives the response sent by the server. I'm not a PHP programmer, but from what I've picked up reading other SO questions, you'd need to do something like:
echo json_encode($returnedData)
in your PHP script. The echo
means that it's part of the output, and json_encode
converts your PHP array into a JSON string, which represents the array in a way that JavaScript actually understands.
Depending on the headers of the response set in your PHP jQuery may or may not automatically parse the string as JSON, passing the resulting object/array to the success handler (as the value of the first argument) rather than just passing along the string response. You can tell it to do that (if you know the response will/should be JSON) by setting the dataType
property in your $.ajax()
call:
request = $.ajax ({
type: "GET",
url: "dataFetcher.php",
data: arg,
dataType: 'json'
});
Then inside your done
handler function response
would be the JavaScript object that matches your PHP array.
Upvotes: 2
Reputation: 1106
You need to eval your response to javascript object
request.done(function(response){
var resultsArray = response.evalJSON();
$("#message").text(resultsArray);
});
or inside ajax call define that you will receive json
request = $.ajax ({
type: "GET",
url: "dataFetcher.php",
data: arg,
dataType: 'json'
});
Upvotes: 0