user1996496 user1996496 - 3 months ago 12
Ajax Question

Why does my JSON data with Ajax not return correctly even though the console logs it?

I am getting a number (1,2,3, etc.) based on coordinates like this:

function getNumber(lat,lng)
{
var params="lat="+lat+"&long="+lng;
$.ajax({
type: "POST",
url: "https://www.page.com/code.php",
data: params,
dataType: 'json',
success: function(data){
if (data.valid==1){
console.log(data);
$("#number").html(data.number);
} else {
console.log(data);
}
},
error: function(){

}
});
}


The problem is, when I check the console, the data is there like this:

[Object]
0 Object
lat: 100.00
long: 50.00
number: 1
etc.


Why doesn't it let me parse it?

The way I return it with POST is:

[{"valid":"1","lat":100.00,"long":50.00,"number":"1"}]

Answer

So you are returning an array?

Then you need to refer to the data by index:

data[0].valid==1
Comments