-1

I have a script that makes an ajax call to a php file, the php file returns two values, a lat and a long.

The ajax response is correct, when checking in firebug I get this response:

[{"latitude":"-0.758623","longitude":"52.047870"}]

This is the code I am using to make the call, what I dont understand is why response.latitude and response.longitude are returned as undefined:

 $.ajax({
        type: "POST",
        url: "http://www.url.com/route/findRoute",
        data: {postcode: postCode},
        dataType: 'json',
        success: function(response)
            {
                alert(response.longitude);
            }
        });

Please can anyone point me in the right direction?

Many thanks

Jim

JimmyBorofan
  • 147
  • 1
  • 13

2 Answers2

3

it is array you have to loop like this:

$.each(response,function(index,item){

    console.log(item);

});

or if it will always be single item then you can access first index like this:

console.log(reponse[0].latitude);
condole.log(reponse[0].longitude);

WORKING FIDDLE

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
1

Since the response is an array. You can loop through all elements like so

response.forEach(function(data){
    console.log(data.latitude);
});
Joseph N.
  • 2,437
  • 1
  • 25
  • 31
  • Thanks, I didn't know it had already converted to an array, I assumed because it was a single request it would natively be and object of one level – JimmyBorofan Jun 29 '14 at 12:59