0

I made a PHP script:

function getData(){

  $DBH = connectDB(********);

  $STH = $DBH->query('SELECT * FROM table');

  $tData = $STH->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($tData);

}

This is executed in getData.php. The fields are ID, name, lastname, age. Basically, get's all the table's values and put them in a JSON array.

I dont know how to complete the JQuery's getJSON function to retrieve, for example, the ID 5 register or the name = "John" one.

The examples at JQuery.com are a bit complex due my little understanding of how all this stuff works.

2 Answers 2

1

UPDATED:

$(function() {
    $.getJSON('getData.php',function(data) {
        $.each(data,function(i, item) {
            alert(item.ID + '->' + item.name + '->' + item.lastname );
        });
    });
});

NB: the way on how you get the single ID, NAME depend on how the json_encode($tData) is formatted, so, you do better if you post to us the echoed json!

Sign up to request clarification or add additional context in comments.

4 Comments

[{"ID":"1","name":"John","lastname":"Doe","age":"22"}...]
i have updated the code, sorry my bad, now it should work as expected! ;)
What's the i for in $.each(data,function(i, item) { ??
@Gabriel A. Zorrilla - i is the incrementer like i++ in a classic for loop
1

$.getJSON("you page.php", { format: "json" }, function(data) { $.each(data.items, function(i,item){ Alert(item["yourfildname"]); }); });

2 Comments

Thanks Marco. But where are you supposed to call the PHP script to retreive the data?
It does not use $.getJSON and i get "undefined" in the alert prompt.

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.