I am trying to send data to php using jquery ajax. The problem is in the below code.
(You can ignore php)
HTML
<ul class="blah">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<div class="result"></div>
JQUERY
$(".blah li").each(function(){
var each_li = $(this).text();
});
$.ajax({
url: 'select-query.php',
method: 'POST',
data: {li_variable: each_li},
success: function(response){
$('.result').html(response);
}
});
each_li returns only one value in ajax function. I can put the ajax in each function but for every li element it performs ajax call. How can i give all li values to ajax data & call ajax only once.
PHP(select-query.php)
<?
$query = "SELECT username FROM table WHERE id = '".$_POST['li_variable']."'";
$query_run = mysqli_query($connect,$query);
while($query_array = mysqli_fetch_assoc($query_run)){
echo $query_array['username'];
}
?>
You can push the data into an array and then send it in ajax request as follows:
var each_li = [];
$(".blah li").each(function(){
each_li.push($(this).text()); //pushing the data in js array
});
$.ajax({
url: 'select-query.php',
method: 'POST',
data: {li_variable: each_li},
success: function(response){
$('.result').html(response);
}
});
You can collect all the element's text content by using map and get,
var each_li = $(".blah li").map(function(){
return this.textContent;
}).get();
Do not fear about .get by thinking that it will do another one iteration to collect the preserved values. It will simply unwrap that value collection from the Jquery object. No iteration will happen under the hood.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With