Home > Net >  loading an ajax call in a while loop
loading an ajax call in a while loop

Time:08-21

I'm having an issue with calling a function in a SQL while clause and can't for the life of me get it to run for each row that is displayed.

while( $Trow = sqlsrv_fetch_array($Tresult, SQLSRV_FETCH_ASSOC) ){

TaskIDX: <?php echo $Trow['IDX'] ?>
<br>
begin get assignment 1
<div id="Assignments-<?php echo $Trow['IDX'] ?>" data-id="<?php echo $Trow['IDX'] ?>)"></div>
<script>

    $(".Assignments").each(function() {
        var Task_IDX = $(this).attr("data-id");
        GetAssignments(Task_IDX);
    });

    function GetAssignments(Task_IDX) {
        $.ajax({
            type: "POST",
            url: "fetchesforajax/fetch_assignments.php",
            data: {Task_IDX: Task_IDX},
            success: function(html){
                console.log(html)
                $('#Assignments-' Task_IDX).html(html);
            }
        })
    }
</script>
<PHP } ?>

And this from the fetch_assignments.php (for now)

$Task_IDX = $_POST['TaskIDX'];

echo 'this is an echo: ' . $Task_IDX;

This is the result. As you can see, it makes the call on the first run but not on the subsequent. It also does not echo the Task IDX.

Any help would be appreciated. enter image description here

CodePudding user response:

I'm going to make some assumptions here, based on some mistakes in the code in the question.

Firstly, it seems that you're creating multiple #Assignmments elements in the DOM given that you're using an each() loop to iterate them. This is the main cause of your problem. When you use an id selector in the DOM, only the first element with that id will be returned. This is because id must be unique; you cannot apply the same id to multiple elements.

The jQuery code you've got is then trying to use a class selector to select those elements, but that will have issues too as it will update all of those elements, not the one related to the AJAX response.

The quick and dirty fix to this is to pass a reference to the .Assignment element to the function which makes the AJAX request:

<!-- in your PHP loop... -->
<div  data-id="<?php echo $Trow['IDX'] ?>)"></div>
$(".assignment").each(function() {
  var taskId = $(this).data('id');
  GetAssignments(Task_IDX, $(this));
});

function GetAssignments(taskId, $assignment) {
  $.ajax({
    type: "POST",
    url: "fetchesforajax/fetch_assignments.php",
    data: {
      Task_IDX: taskId
    },
    success: function(html) {
      $assignment.html(html);
    }
  })
}

This will work, but still has the underlying problem that you are flooding your server with requests.

A better approach would be to build an array of all the data-id values and send a single request to the server. The response to this request would include all the data for each element, ideally in JSON format, ready for all the .assignment elements to be updated in one loop.

Note that this would require amending how your fetch_assignments.php logic accepts and returns data, which I'll leave to the OP to research as I'm not a PHP developer, but the JS would look something like this instead:

function GetAssignments() {
  let assignmentIds = $('.assignment').map((i, el) => el.dataset.id).get();

  $.ajax({
    type: "POST",
    url: "fetchesforajax/fetch_assignments.php",
    data: {
      ids: assignmentIds
    },
    success: function(response) {
      // assuming that 'response' is an array of 'assignment' objects:
      response.forEach(assignment => {
        // create/update the HTML as required here...
      });
    }
  })
}
  • Related