javascriptjqueryajax

ajax return data in database out of order


function selectDiv() {
<?php
$stmt = $conn->prepare("SELECT id, name  FROM data");
$stmt->execute(); 
$stmt->bind_result($id ,$name);
while ($stmt->fetch()) {?>
    add (<?php echo "'$id'";?>,<?php echo "'$name'";?>);
<?php } ?>
}

function add (id , name) {
    $.post("type.php",{id:id, name:name}, function (data) {
    add2 (id, name, data);
}); 
document.getElementById("div").innerHTML += name + "<br>";
}

function add2 (id , name, type) {
    document.getElementById("div").innerHTML += name + "|"+ type + "<br>";
}

I retrieve data from data base using $.post and on each turn I call function add to append a certain div. the problem is that the data comes out of order. How can I fix it?


Solution

  • Try this if is possible:

    function selectDiv() {
     <?php  $stmt = $conn->prepare("SELECT id , name, t2.type  FROM data INNER JOIN t2 ON join_condition1”);
     $stmt->execute(); 
     $stmt->bind_result($id ,$name);
     while($stmt->fetch()) {?>
     add (<?php echo "'$id'";?>, <?php echo "'$name’”;?>, <?php echo "'$type’”;?>);
     <?php } ?>
     }
    
    function add (id , name, type){
    document.getElementById("div").innerHTML += name + "<br>" + "|"+ type + "<br>";
    }