Emma Emma - 3 days ago 5
JSON Question

How to post arrays from PHP file into a table using JQuery $.getJSON?

I am trying to output an array to a table, based on a user entered variable called

firstname
. If two arrays have the same
firstname
value the table should display both arrays. Currently, only the first array is being displayed in the table. I have included my current code below:

$(document).ready(function() {
var url = "data.php";

$('#getJSON').click(function(event) {
event.preventDefault();
var firstname = $('#firstname').val();
url = url + "?firstname=" + firstname;

$.getJSON(url, function(json) {
var tr;
for (var i = 0; i < json.data.length; i++) {
tr = $("<tr/>");
tr.append("<td>" + json.data[0].id + "</td>");
tr.append("<td>" + json.data[0].title + "</td>");
tr.append("<td>" + json.data[0].firstname + "</td>");
$('table').append(tr);
}
});
});
});


PHP script:

if ($firstname === "Emma")
$arr[] = array('id'=> "1", 'title'=> "Miss", 'firstname'=> "Emma", 'surname'=>"Brown");
else if ($firstname === "Emma")
$arr[] = array('id'=> "2", 'title'=> "Mrs", 'firstname'=> "Emma", 'surname'=>"Green");
else
$arr[] = array('id'=> "Unknown", 'title'=> "Unknown", 'firstname'=> "Unknown", 'surname'=> "Unknown");

echo '{"firstname":'.json_encode($arr).'}';


I would like it to output like so:
ExampleTable

Any help is much appreciated!

Answer

You have two mistakes:

First one is the use of the if clause. Since you are using if elseif you cannot put the same condition in both if and elseif.The else if means if previous condition is false then check another condition. In this case the elseif will never be executed since the first condition is true.

Second you are always storing data in the same index of your results array so you will overwrite your data and always get one element in this array.

$id=1;
$arr=array();

if ($firstname === "Emma"){
    $arr[] = array('id'=> $id++, 'title'=> "Miss", 'firstname'=> "Emma", 'surname'=>"Brown");
    $arr[] = array('id'=> $id++, 'title'=> "Mrs", 'firstname'=> "Emma", 'surname'=>"Green");
 }

 else if($firstname === "NotEmma")
     $arr[] = array('id'=> $id++, 'title'=> "Miss", 'firstname'=> "NotEmma", 'surname'=>"xx");

 else
        $arr[] = array('id'=> "Unknown", 'title'=> "Unknown", 'firstname'=> "Unknown", 'surname'=> "Unknown");

echo '{"firstname":'.json_encode($arr).'}';
Comments