0

If I am populating a list with MySQL data using the following:

HTML

<ul id="first_column"></ul>
<br>
<ul id="second_column"></ul>

JQUERY/AJAX

$(document).ready(function() { 
  $.ajax({
    url: "filename.php",
    success: 
    function(data){            
        $("#first_column").html(data);
    }
  })
})

PHP

$conn = OpenCon();

$sql = "SELECT first_column FROM table";

$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){

    while ($row = mysqli_fetch_assoc($result)) {        
        echo '<li>' .$row['first']. '</li>';
    }
}

How can I add a second SQL query (SELECT second_column FROM table) to the PHP and output it to <ul id="second_column"></ul> from the returned AJAX data? I think I have to use arrays and json, but I am struggling to figure it out.

1 Answer 1

2

Change your PHP to echo a json encoded string.

$conn = OpenCon();

$first_column = '';
$second_column = '';

$result = mysqli_query($conn, "SELECT first_column FROM table");
if(mysqli_num_rows($result) > 0){
    while ($row = mysqli_fetch_assoc($result)) {  

        //append to `$first_column` instead of echoing directly      
        $first_column .= '<li>' .$row['first']. '</li>';
    }
}

//generate `$second_column` the same way as `$first_column`
$result = mysqli_query($conn, "SELECT second_column FROM table");
if(mysqli_num_rows($result) > 0){
    while ($row = mysqli_fetch_assoc($result)) {  

        //append to `$second_column`
        $first_column .= '<li>' .$row['second']. '</li>';
    }
}

//send both `$first_column` and `$second_column` at the same time
echo json_encode(['first_column' => $first_column, 'second_column' => $second_column]);

Then, in your ajax, you can select whichever column you want.

$(document).ready(function () {
    $.ajax({
        url: "filename.php",
        dataType: "json",
        success: function (data) {
            $("#first_column").html(data.first_column);
            $("#second_column").html(data.second_column);
        }
    })
});

Alternatively, you could do a separate Ajax call.

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

Comments

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.