Reputation: 1089
I am trying to encode my array results to json and pass them to a ajax successful event in javascript.
PHP
$results = array(
"time1" => 1,
"time2" => 2,
);
echo json_encode($results);
JAVASCRIPT / JQUERY
$.ajax({
type: "POST",
url: "actions/myphp.php",
data: PassArray,
dataType: 'json',
beforeSend: function (html) { // this happens before actual call
// alert(html);
},
success: function (html) {
// $("#loginoutcome").text(html);
// alert(html);
var obj = jQuery.parseJSON(html );
// Now the two will work
$.each(obj, function(key, value) {
alert(key + ' ' + value);
});
},
Leaving the JQUERY.parseJSON there throws a json parse unexpected character, I dont think I that I need it anyway as I specify in the dataType: 'json', above?.. But how can I retrieve the values ??
Thanks
Upvotes: 0
Views: 1316
Reputation: 49919
As you pass datatype as JSON, jQuery will give you back the JSON object, you don't have to parse it anymore.
So make it like this:
success: function (obj) {
$.each(obj, function(key, value) {
alert(key + ' ' + value);
});
},
If you know its time1 or time2, you can do this:
success: function (obj) {
alert(obj.time1);
alert(obj.time2);
},
Upvotes: 2