0

I have several div tags that I would like to be updated with several different mysql queries.

My code below only updates one of these divs, how can I expand it to 1-6 and also leave room for expansion in the future for more divs?

I also need to be able to update each div individually with a specific query for a specific table.

<html>

<div id="1"> </div>
<div id="2"> </div>
<div id="3"> </div>
<div id="4"> </div>
<div id="5"> </div>
<div id="6"> </div>
//...and so on

</html>

<script type="text/javascript">

$(document).ready(function () {
function display($id) {
    $.ajax({
        async: false,
        type: "POST",
        url: "apifile.php",
        data: {id:$id},
        dataType: "json",
        success: function(msg) {
            if(msg.success) {
                $($id).next(".one").html(msg);
            } else {
                alert("error");
            }
        }
    });
}

</script>

<?php

mysql_connect(host, user, pass);
mysql_select_db(name);
mysql_query("select round((count(*)*100)/(select count(*) from test),1) as percent from test group by field1 order by percent desc");

$reply['success'] = "Success"; 
if($return = display($id)) {
    $reply['success'] = "Success";
} else {
    $reply['error'] = "Error";
}
echo json_encode($reply);

?>
1
  • Why not just make one Ajax call and return an array of the data you need? (given its the Se database) Then you can just loop through that array with jQuery printing the DIVs and the data as you go. Commented Mar 11, 2015 at 11:05

2 Answers 2

1

you can store the data/messages/otherinfo from each query in different portions of your $reply array

query1 goes here ...

   $reply[1]['success'] = "Success"; 
if($return = display($id)) {
    $reply[1]['success'] = "Success";
} else {
    $reply[1]['error'] = "Error";
}

query2 goes here ...

$reply[2]['success'] = "Success"; 
$reply[2]['data'] = "3,4,5"; 

query3 goes here ...

$reply[3]['success'] = "Success"; 
$reply[3]['data'] = "beans,soup,guac"; 

echo json_encode($reply);
Sign up to request clarification or add additional context in comments.

Comments

1

You can add a class to the div and run the ajax on class

$( ".div" ).each(function() {
    var div_id = $(this).attr('id');
    display(div_id);
});

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.