skip to Main Content

I currently have my HTML site set up where I pass a div id as data into my Ajax.

<div id="1" class="stats">
    DATA GOES IN HERE
</div>
<div id="2" class="stats">
    DATA GOES IN HERE
</div>

I have it so that when the page first loads, an Ajax call is loaded that finds the div id and makes use of it back-end to bring the DATA forward.

$(document).ready(function(){
var fId = $(".stats").attr("id");
$.ajax({
    url: 'get_stats',
    type: 'GET',
    data: {fId : fId},
    success: function(data) {
        $("#"+fId).html(data);
    },
    error: function(data){
        alert("ERROR: " + data);
    }
});
});

The data can be brought. However, I have about 26 of these divs and I need to do this call 26 times. The problem is, the call is only made once and the data is only loaded for the very first div.

How can I make it so that I pass the data from all 26 divs into the Ajax call and bring it into the HTML when the page is first loaded?

2

Answers


  1. You can just do that with a loop like:

    let divs = $(".stats");
    
    $.each(divs, function (div) {
         //..do your ajax request here
    });
    
    Login or Signup to reply.
  2. Please try this

    $(document).ready(function(){
       $(".stats").each((i,e)=>{
         let fId=$(e).attr("id");
         $.ajax({
           url: 'get_stats',
           type: 'GET',
           data: {fId : fId},
           success: function(data) {
             $("#"+fId).html(data);
           },
           error: function(data){
             alert("ERROR: " + data);
           }
         });   
       })
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="1" class="stats">
        DATA GOES IN HERE
    </div>
    <div id="2" class="stats">
        DATA GOES IN HERE
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search