Using jQuery and PHP I got json array, but somehow I can't manage to get data out of it. Can anyone explain why this happens?
$.ajax({
type: "POST",
url: "php/global_functions.php",
data: {callFunction: "getNewsTitles"},
cache: false,
success: function(result){
alert(result);
//[{"heading":"Ritens pie sienas tiek nozagts","text":"Zilu 2008.gada BMW m\u0113s at\u013cauties tom\u0113r nevaram"},{"heading":"Dzied\u0101t\u0101ja Aliwka par CityTaxi","text":"Teksts 123 Teksts"},{"heading":"Kvalit\u0101tes uzlabo\u0161ana P\u0101rdaugav\u0101","text":"Fant\u0101zija nozaga kaimi\u0146a ka\u0137i"},{"heading":"CityTaxi papla\u0161ina autoparku","text":"Fant\u0101zija sit augstu vilni"},{"heading":"CityTaxi iekaro R\u012bgu","text":"Te iet kaut k\u0101ds teksts, piem\u0113ram - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris pellentesque nisl id lobortis congue. Ut commodo tortor eget dapibus gravida. Sed accumsan orci ac ante dignissim feugiat."}]
alert(result[1].heading);
//undefined
}
});
I commented results which appears on alerts. Why does it give me undefined?
Ali
22.4k15 gold badges86 silver badges102 bronze badges
-
try parsing the string into json first: var json = JSON.parse(result);John M– John M2015年05月23日 23:41:39 +00:00Commented May 23, 2015 at 23:41
1 Answer 1
Just parse the result using:
var returnedData = JSON.parse(response);
You can also set the datatype to be JSON:
$.ajax({
type: "POST",
dataType: "json",
url: "php/global_functions.php",
data: {callFunction: "getNewsTitles"},
cache: false,
success: function(result){
alert(result);
alert(result[1].heading);
}
});
Or use the $.getJSON jQuery method.
answered May 23, 2015 at 23:55
Yam Mesicka
6,6518 gold badges51 silver badges70 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js