'Jquery Ajax loop request problem with attribute

I want to get the name of two contestants from the database using PHP loop and at the same time calculate the total vote of each candidate and display it using ajax jquery but am only getting the first candidate votes while the other candidate is not even showing anything, not even 0.

index.php

<h4 class="header-title mb-3">Presidential Result</h4>
<div class="">
   <div class="row text-center">
    <?php
        $sql = "SELECT * FROM contestants WHERE post='president'";
        $query = mysqli_query($conn, $sql);
        while($row=mysqli_fetch_array($query)){
     ?>
      <div class="col-md-6">
        <p class="text-muted mb-0 mt-3" id="contestname"><?php echo $row['fullname']?></p>
         <h2 class="fw-normal mb-3" id="precount">
                                                    
          </h2>
      </div>
   <?php
      }
    ?>                                                
 </div>

The index.php only displays the name of the contestants/candidates.

Query.js

function view_pres_count(){
    var presname =$('#contestname').html();
    
    $.ajax({
        url: 'prescount.php',
        method: 'post',
        data:{present:presname},
        success: function(data){
            data = $.parseJSON(data);
            $('#precount').html(data.html);
        }
    })

}

in Query.js I passed each name to presname using the tag id. At this point even without the ajax request, if I log presname to console I only got the first candidate name. Any way out of this?



Solution 1:[1]

IDs need to be unique. Change to class and do

const presnames = $('.contestname').map(function() {
  return this.textContent.trim()
}).get()
console.log(presnames)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<h4 class="header-title mb-3">Presidential Result</h4>
<div class="">
  <div class="row text-center">
    <div class="col-md-6">
      <p class="text-muted mb-0 mt-3 contestname">
        Jimmy Carter
      </p>
      <h2 class="fw-normal mb-3" class="precount">
      </h2>
    </div>
    <div class="col-md-6">
      <p class="text-muted mb-0 mt-3 contestname">
        Ulyssus Grant
      </p>
      <h2 class="fw-normal mb-3" class="precount">

      </h2>
    </div>
  </div>

You will need to give more details of your precount html but I suggest you return an array and loop over

$(".precount").each(function(i) { $(this).html(data[i].html) })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1