Reputation: 11
I'm new to jQuery. I'm trying to get some data from MySQL via AJAX. My PHP returns JSON. This is the response (don't mind variables names. It's in Czech :)):
[{"nadpis":"Testovac\u00ed nadpis","text":"Testovac\u00ed \u010dl\u00e1nek o tom jak se zase prohr\u00e1lo","sestava":"Nikdo nehr\u00e1l"},{"nadpis":"Druhej nadpis","text":"Druhej text","sestava":"druh\u00e1 sestava"}]
Here is my jQuery function:
$.ajax({ type: 'GET',
url: 'db.php',
datatype:'json',
success : function(data)
{ console.log(data[1].text);
console.log(data);
}
});
The problem is that when I want to access data[1].text, it only returns undefined. I went through a lot of answers here on StackOverflow and other forums, but I still can't make it work.
Upvotes: 1
Views: 3628
Reputation: 817128
Change datatype
to dataType
. Otherwise jQuery doesn't recognize the option and won't parse the response for you.
In your case, data
is still a string, which you can verify with console.log(typeof data)
. data[1]
returns "{"
, and "{".text
is undefined
.
Have a look at the documentation for the correct option names: http://api.jquery.com/jquery.ajax/
Alternatively, you could parse the response yourself.
(I posted an answer to prevent other misguiding answers. It's community wiki because I voted to close the question.)
Upvotes: 2