theplau
theplau

Reputation: 980

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"}]

Upvotes: 0

Views: 26

Answers (1)

HaukurHaf
HaukurHaf

Reputation: 13806

So you are returning an array?

Then you need to refer to the data by index:

data[0].valid==1

Upvotes: 3

Related Questions