Jquery Ajax loop request problem with attribute - php

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?

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) })

Related

Codeigniter Jquery. How to display data into cards using loop for e-commerce

Help i want to display all of this data in cards. the code already can get the result from model to only problem is to display. my plans is when i click the burgers category it will display all the data in card-body and when i press beverages it will display all the beverages without refreshing. for some reason i need to use jquery.. IMAGE LINK: https://imgur.com/a/2DsBKqG
View:
<div class="col-sm-9" style="border:solid 1px;">
<div class="row">
<div class="col-sm-4">
<div class="card">
<div class="card-body">
<div class="product-grid">
<div class="product-image">
<a href="#" class="image" style="background-color:#F3F3F3;">
<img class="pic-1" src="https://media.comicbook.com/2020/05/dragon-ball-super-when-will-
should-goku-master-ultra-instinct-1219439.jpeg?
auto=webp&width=1200&height=628&crop=1200:628,smart" class="d-block w-100">
</a>
<a class="add-to-cart" href=""> + </a>
</div>
<div class="product-content">
<h3 class="title">Product Name</h3>
<div class="price"></div>
</div>
<div class="action-buttons">
<a class="btn-outline">ADD TO CART</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Jquery:
function searchcategory(category_id)
{
$.ajax(
{
url:"<?php echo base_url() ?>admin/getproducts/"+category_id,
type:"POST",
dataType:"json",
success:function(data)
{
data.forEach(key =>
{
let row = `<div class="price" id="price" >${key.price}</div>`;
});
}
});
}

using while loop inside ajax

I'm trying to use a while loop inside in PHP And Ajax.
But I only get the First ID, not the 2nd, 3rd and so on.
Here is the code Of PHP:
<div class="container pt-5 my-5">
<section class="p-md-3 mx-md-5 text-center">
<h2 class="text-center mx-auto font-weight-bold mb-4 pb-2">Our Team</h2>
<div class="row">
<?php while ($t_run=mysqli_fetch_array($t_query)){?>
<div class="col-lg-3 col-md-4 col-sm-6 mb-4">
<div class="p-4">
<div class="avatar w-100 white d-flex justify-content-center align-items-center">
<input type="hidden" name="team" class='team_id' value="<?php echo $t_run['id']?>">
<img src='images/<?php echo $t_run['img']?>'class="team_img rounded-circle z-depth-1-half"/>
</div>
<div class="text-center mt-2">
<h6 class="font-weight-bold pt-2"><?php echo $t_run['name']?></h6>
<p class="text-muted">
<small><i><?php echo $t_run['title']?></i></small>
</p>
<button class="team btn-info border-0 p-2 rounded">View profile</button>
</div>
</div>
</div>
<?php }?>
</div>
</section>
and here is the Ajax code I use
<script type="text/javascript">
$(document).ready(function () {
$('.team').click(function (){
var name = $('.team_id').val();
$('#content_container').load('team-ajex.php',{
id:name
});
});
});
</script>
I'd recommend you to try to change
$('.team_id').val()
to
$(this).parent().parent().find('input[name="team"]').val()
When you try to get $('.team_id') it returns an array of all inputs with this class...

How to populate jquery data accordingly/individually to Cards?

Im new to Laravel framework and im trying to develop a simple car listing web using Bootstrap Cards. I've successfully implemented AJAX Get including populating data from Controller using Jquery append() method. However it is displaying all cars in one Card. How to populate each Cards containing each car?. current result console.log result
public function GetCars(Request $request)
{
if ($request->ajax())
{
$cars = Car::all();
return response()->json( $cars );
}
}
<div class="album py-1">
<div class="container bg-light">
<div class="row py-2">
<div class="col-md-3">
<div class="card mb-3 shadow-sm">
<div class="hover-container">
<img src="" class="image img-thumbnail">
<a class="Viewbtn text-decoration-none" href="#" style="font-size: small">View</a>
</div>
<div class="card-body CarDetail">
<p class="card-text font-weight-bold">Make:<span class="car_Make"></span></p>
<p class="card-text font-weight-bold">Model:<span class="car_Model"></span></p>
<div class="d-flex justify-content-between align-items-center">
<p class="font-italic table_data">Price: RM <span class="car_Year"></span></p>
</div>
</div>
</div>
</div>
</div>
</div>
<button id="testbtn" type="submit" class="btn btn-success">AJAX</button>
</div>
<script>
$(document).ready(function(){
$('#testbtn').click(function () {
$.ajax({
type: 'GET',
url: '/ajax/getCar',
success : function (data) {
$.each(data, function( i, car ) {
$('.car_Make').append(car.make);
$('.car_Model').append(car.model+'<br>');
$('.car_Year').append(car.year+'<br>');
});
}
});
});
});
</script>
This is what are you meaning?
I created an example, where I'm using some rows from your console.log data.
Explanation:
I am iterating throught the data array. If it is first iteration I'm adding data (one CarDetail div exists in your code.
For the next iterations I am cloning the CarDetail div and fill with next data.
Of course,there are more posibilities how to add your data to page. For example, you can fill the first item in page and then iterate from the second to the last (in that case you won't need the if/else condition) or you can add the HTML code in a JS variable. Personally, I wouldn't do that because it looks very ugly and the readability of the code could get worse.
$(document).ready(function(){
var data = [
{id:31,make:"Audi",model:"R8",year:2000},
{id:32,make:"Ferrari",model:"FF",year:2000},
{id:33,make:"Mazda",model:"Rx-7",year:2000},
{id:34,make:"Ferrari",model:"F12",year:2012},
{id:35,make:"Porsche",model:"911",year:2015},
{id:36,make:"Land Rover",model:"Vogue",year:2015},
{id:37,make:"Mercedes Benz",model:"SL350",year:2013},
{id:38,make:"Ferrari",model:"F12",year:2013},
{id:39,make:"Ferrari",model:"458",year:2013},
];
$.each(data, function( i, car ) {
if(i == 0) {
$('.card').find('.car_Make').text(car.make);
$('.card').find('.car_Model').text(car.model);
$('.card').find('.car_Year').text(car.year);
} else {
var carDetailCloned = $('.card').first().clone();
carDetailCloned.find('.car_Make').text(car.make);
carDetailCloned.find('.car_Model').text(car.model);
carDetailCloned.find('.car_Year').text(car.year);
$('.card-container').append(carDetailCloned);
}
});
});
.CarDetail{background-color:red;margin-bottom:2em}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="album py-1">
<div class="container bg-light">
<div class="row py-2">
<div class="col-md-3 card-container">
<div class="card mb-3 shadow-sm">
<div class="hover-container">
<img src="" class="image img-thumbnail">
<a class="Viewbtn text-decoration-none" href="#" style="font-size: small">View
</a>
</div>
<div class="card-body CarDetail">
<p class="card-text font-weight-bold">Make:
<span class="car_Make"></span>
</p>
<p class="card-text font-weight-bold">Model:
<span class="car_Model"></span>
</p>
<div class="d-flex justify-content-between align-items-center">
<p class="font-italic table_data">Price: RM
<span class="car_Year"></span>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
<button id="testbtn" type="submit" class="btn btn-success">AJAX</button>
</div>
Edit: I edited my code to clone <div class="card mb-3 shadow-sm" for every card and add data in there. Moreover, I add a card-container class in the parent element to use it when I append a new car. Is that enough?

Fetch data from mysql by checking radio button

i have few models of products and when i click on each model to show me his variants, like on image from below
Here is what i made in html :
<div class="owl-carousel owl-theme no-pb slide-arrow-2" data-
dots="false" data-nav="true" data-items="4" data-lg-items="3"
data-md-items="2" data-sm-items="2" data-margin="30" data-
autoplay="false">
<?php
$qua = "SELECT * FROM produse WHERE categorie = '$id' ORDER BY pozitie";
$qla = mysqli_query($conn, $qua);
while($rova = mysqli_fetch_assoc($qla)){?>
<?php
$id_paletar = $rova['id'];
$sql2=mysqli_query($conn,"SELECT * FROM pret_produse WHERE produs_id='$id_paletar'");
$pret2=mysqli_fetch_array($sql2);
?>
<div class="item">
<div class="product-item">
<div class="product-img">
<img class="img-fluid" src="cms/produse/<?=$rova['poza'];?>" alt="">
<div class="product-overlay">
<ul class="list-unstyled">
</ul>
</div>
</div>
<div class="product-btn ifix">
<div class="btn btn-theme btn-block btn-new" ><span style="font-size: 15px;"><?=$rova['titlu'];?></span>
<div>
<label class="containere">
<input type="radio" name="produse" id="paletar_pret" class="palt" value="<?=$rova['id'];?>">
<p class="checkmark"></span>
</label>
</div>
</div>
</div>
</div>
</div>
<?php }?>
</div>
Here is my jquery:
$(document).ready(function(){
$('.palt').change(function() {
if(this.checked) {
var check= $(this).val();
alert(check);
$.ajax({
url: 'cere_cotatie.php',
type: 'POST',
data: {check:check},
success: function(data){
$('.fetch').append(data);
}
});
}
});
And here is my php file which i use on ajax to call:
<?php
if($_POST)
{
include('config.php');
echo $check = $_POST['check'];
$s = "SELECT * FROM variante WHERE id_var='$check'";
$q = mysqli_query($conn, $s);
while ($r = mysqli_fetch_assoc($q)) {?>
<div class="item" style="width:220px;">
<div class="product-item">
<div class="product-img">
<img class="img-fluid" src="cms/variante/<?=$r['poza'];?>" alt="">
<div class="product-overlay">
<ul class="list-unstyled">
</ul>
</div>
</div>
<div class="product-btn ifix">
<div class="btn btn-theme btn-block btn-new" ><span style="font-size: 15px;"> <?=$r['denumire'];?></span>
<div>
<label class="containere">
<input type="checkbox">
<p class="checkmark"></span>
</label>
</div>
</div>
</div>
</div>
</div>
<?php }?>
<?php }
?>
My problem is like this if i check first box to display me variants of what i checked but my code is doing this way, if i check first box is loading data and after that if i check another box results from first box need to dissapear and to be only what i check.
EDIT: in that print screen you can see the problem.
I think you should add below code
$('.palt').change(function(e) {
e.preventDefault();
});
and remove alert(check);
Hope it work for you.

PHP MYSQL "more info" button

I have a question:
In PHP, HTML and MySQL I have made an overview of products (data from database)
Now each product in this list has a more info button. I want, when I click more info, that a new page is opened and that page should show more info about that product.
How do I make it work that it only shows the info of that particular product?
This is the current code of the table with the overview:
<div class="col-xs-2">
</div>
<div class="col-xs-4">
<h4 class="product-name"><strong> Producten</strong></h4><h4><small></small></h4>
</div>
<div class="col-xs-6">
<div class="col-xs-6 text-right">
<h6><strong>Datum binnenkomst</strong></h6>
</div>
<div class="col-xs-4">
<h6><strong>Datum uitgave</strong></h6>
</div>
<div class="col-xs-2">
</div>
</div>
</div>
<hr>
<?php
include("connection.php");
$sql = "SELECT * FROM bedrijven";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo'
<div class="row">
<div class="col-xs-2"><img class="img-responsive" style="max-height:80px;" src="' . $row["KVK"] . '">
</div>
<div class="col-xs-4">
<h4 class="product-name"><strong> '. $row["Bedrijfsnaam"] .' </strong></h4><h4><small>'. $row["Klantnummer"] .'</small></h4>
</div>
<div class="col-xs-6">
<div class="col-xs-6 text-right">
<h6><strong>'. $row["BStraatnaam"] .'</strong></h6>
</div>
<div class="col-xs-4">
<h6><strong>'. $row["BHuisnummer"] .'</strong></h6>
</div>
<div class="col-xs-2">
<a href="Moreinfo.php"> <button type="button" class="btn btn-link btn-xs">
More info
</button></a>
</div>
</div>
</div>
<hr>';
}
} else {
echo "0 results";
}
$conn->close();?>
I hope someone would help me.
It would be nice to learn more and new things;)
If you want to split up results only print out what you want to show. You can do selective queries with LIMIT (for a range) or just make sure you only get one result usually done by using a unique identifier (an auto-incremented ID field) and WHERE id = 1.
And in PHP we can use $_GET['page'], to get the page parameter from an url like:
domain.com/somepage?page=2
However remember that this is easily edited by the end user in the location bar and thus should be properly handled in PHP before using it in a SQL query to avoid SQL injection. It be checking with PHP's is_number or using something like prepared statements

Categories