Emma Emma - 1 year ago 68
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

. If two arrays have the same
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) {
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>");

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");
$arr[] = array('id'=> "Unknown", 'title'=> "Unknown", 'firstname'=> "Unknown", 'surname'=> "Unknown");

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

I would like it to output like so:

Any help is much appreciated!

Answer Source

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.


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

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

echo '{"firstname":'.json_encode($arr).'}';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download