2

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).

3 Answers 3

3

If there is only a single object returned then you can easily access each field. You already know the field names so use them.

$.getJSON("get.php", function(result) {
    console.log(result.id); 
    console.log(result.title);
    console.log(result.description);
    console.log(result.url);
});
Sign up to request clarification or add additional context in comments.

Comments

0

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
});

2 Comments

Ok, fine. But how I can access mySQL fields by field name? I saw codes that use the notation 'field.title'.
You don't need to use $.each to iterate over them. Remove that part and just use result.id, result.title and so on
0

Try this, use parseJSON and then try to access :

$.getJSON("get.php", function(result) {
    var obj = JSON.parse(result);
    $.each(obj, function(key, field){
     console.log(key); // here you will get index like id,title
     console.log(field); // here you will get value
    });
});

3 Comments

I get -> SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data. Where could Json data be wrong?
Ok try var obj = JSON.parse(result)
Sorry, same syntax error and now error also on var obj = JSON.parse(result). I would like to access data like this: 'field.title'. I see that 'field' and 'key' work but I looking for 'field.title'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.