Nicero Nicero - 7 months ago 16
PHP Question

Access mySQL fields using Ajax and PHP

After lot of temptatives and after reading lot of posts about I'm still unable to read mySQL fields using Jquery. My PHP code, which connects to a db and gets some data, outputs the following using

echo json_encode($html);
:

{"id":"1","title":"this_is_title","description":"this_is_description","url":"this_is_url"}


I then try to read the single fields but I keep getting "undefined". For example:

$.getJSON("get.php", function(result) {
$.each(result, function(key, field){
console.log(field.title);
});
});


If I simply use
field
instead of
field.title
it works but I get all the fields (of course).

Answer

Your JSON data contains only a single object, not an array of objects.

You are iterating over each property within this JSON object with $.each, so within that callback function key will be the property name and field will be the property value.

Change your console log call to this:

console.log(field);

and you can see the difference, the value will of the property will be logged.

You can access the properties of the JSON directly like so:

$.getJSON("get.php", function(result) {
     console.log(result.id);
     console.log(result.title);
     // etc
});