user2495761
user2495761

Reputation:

JSON Return List from Array

I'm trying to generate a list of names with checkboxes using AJAX. Unfortunately, using the code below, I only get one name back instead of the four that are in my database.

Here is the code I'm using which sits in a separate php file called by AJAX:

$query = "SELECT id, first_name, last_name, email FROM users WHERE location_id = '{$location_id}' ";

    $result = mysqli_query($connection, $query);
    if (!$result) {
        die("Database query failed: " . mysqli_error($connection));
    }

while ($row = mysqli_fetch_array($result)) {
        $name = $row['first_name'] . " " . $row['last_name'];
        $attendees = '<label><input type="checkbox" name="emp_name[]" id="emp_name[]" value="' . $name . '"> ' . $name . '</label><span style="padding-right: 20px;"></span>';
}

echo json_encode(array('attendees'=>$attendees));

Before I attempted this AJAX call I had the same query in my main document with echo instead of $attendees and it worked flawlessly. It returned all four names with checkboxes next to them. Here's a snippet from that code:

while ($row = mysqli_fetch_array($result)) {
                $name = $row['first_name'] . " " . $row['last_name'];
                echo '<label><input type="checkbox" name="emp_name[]" id="emp_name[]" value="' . $name . '"> ' . $name . '</label><span style="padding-right: 20px;"></span>';
            }

I'm very new to AJAX and so I'm not sure where the problem is. Please help!

Upvotes: 0

Views: 56

Answers (2)

gview
gview

Reputation: 15361

I don't think you understand the point of json. It's a way to encode the data.

You are trying to pass back the html markup rather than the raw data, json encoded. If you want to do that, then lose the json, and simply add or replace the html you get from the ajax call in your frontend code, using javascript like this:

document.getElementById("emplist).innerHTML = ...

Otherwise, your fetch loop should be more like this:

while ($row = mysqli_fetch_array($result)) {
    $attendees[] = $row;        
}
echo json_encode(array('attendees' => $attendees));

Either way, you still need $attendees[] = so you store each row to an array.

Upvotes: 0

Eugen Rieck
Eugen Rieck

Reputation: 65284

You overwrite $attendees with every iteration.

  • If you want an array, use $attendees=array(); before the loop and $attendees[] = '<la.. inside the loop
  • If you want concatenation, use $attendees=''; before the loop and $attendees .= '<la.. inside the loop

Upvotes: 1

Related Questions