Home > Back-end >  Ajax request made but position of value in returned response as array keeps changing. how do I fix t
Ajax request made but position of value in returned response as array keeps changing. how do I fix t

Time:02-22

I have a script which sends an array of numbers via Ajax to a web server.

The values are used to query a database and then the corresponding values of those numbers In the table are sent back which I then send to respective divs in my html file

see below.

function getData() {

  var faq_get = Array("1", "2", "3");


  var faq_async_request = [];
  var responses = [];
  for (i in faq_get) {
    // you can push  any aysnc method handler
    faq_async_request.push($.ajax({
      url: "https://###########.com/data/data.php", // your url
      method: "post", // method GET or POST
      data: {
        mid: faq_get[i]
      },
      success: function (data) {
        console.log("success of ajax response");
        responses.push(data);
        
      }
    }));
  }

  $.when.apply(null, faq_async_request).done(function () {
    // all done
    console.log("all request completed");
    console.log(responses);

    $("#3").html(responses[2]);
    $("#2").html(responses[1]);
    $("#1").html(responses[0]);
  });
}

PHP SCRIPT BELOW

 $fig = $_POST['mid']; 

$sql = "SELECT * from data where id = '$fig'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo $row["scores"];
  }
 }

my Ajax script sends these data and receives the responses as I wanted, but the I have one small issue. The position of the values gets swapped from time to time.

pls see image below

position of response data getting swapped

CodePudding user response:

You need to process the responses in the $.when callback, so that you process them in the order that they were sent, not when the responses were received.

function getData() {

  var faq_get = Array("1", "2", "3");

  var faq_async_request = faq_get.map(id => $.ajax({
    url: "https://###########.com/data/data.php", // your url
    method: "post", // method GET or POST
    data: {
      mid: id
    }
  }));

  $.when(...faq_async_request).done(function(...responses) {
    // all done
    console.log("all request completed");
    responses = responses.map(resp => resp[0]); // get the first value from each promise
    console.log(responses);

    $("#3").html(responses[2]);
    $("#2").html(responses[1]);
    $("#1").html(responses[0]);
  });
}

  • Related