I am new to AJAX I've been struggling to code on ajax, but i am enjoying it. my problem is i have a looping data where in each has a vote link functionality. I was able to do the ajax function but once i click on each data it give me one value only which is the first value i am getting from the database. Here's my code:
<span id="question">Vote for your Recipe!</span>
<?php $getData = $recipes->getBreakfast(); foreach($getData as $data) { ?>
<div class="item"><?php echo $data['recipe_id'] ?> </div>
<div class="score"><?php echo $data['vote']; ?></div>
<div class="a">Vote<?php echo $data['recipe_title']; ?></div>
my ajax:
$(document).ready(function() {
var self = $(this);
//var id = $(".item").html();
var score = $(".score").html();
$.ajaxSetup({
url: 'insert_vote.php',
type: 'POST',
cache: 'false',
});
$(".a").click(function() {
alert(score);
//self.find('.score').html(++score);
return false;
});
});
Vote for your Recipe!
6
Vote CHICKEN
0
Vote ADOBO
4
Vote HOTDOG
I am only getting the 6 score value even if i click on the other recipe
remove
var score = $(".score").html();
and use
$(".a").each(function() {
$(this).click(function() {
var score = $(this).prev().html();
alert(score);
return false;
});
});
Related
I have a page and I am displaying the list(MAX 200 records) on my page using ajax.
I am using the below code to call the ajax and show the response on the page.
And the second script is for a button called "Load More". I have to show the 20 records on the page then the user clicks on load more than displays the next 20 records.
Now, My issue is, I am getting all the records and load more button
$(document).ready(function(){
$.ajax({
url: 'function21.php',
method:'post',
dataType: "json",
data:{action:"employeelist21"},
success: function(data){
$('#employeelist').append(data);
}
})
});
$(document).ready(function(){
var list = $("#employeelist21 li");
var numToShow = 20;
var button = $("#next");
var numInList = list.length;
//alert(numInList);
list.hide();
if (numInList > numToShow) {
button.show();
}
list.slice(0, numToShow).show();
button.click(function(){
var showing = list.filter(":visible").length;
list.slice(showing - 1, showing + numToShow).fadeIn();
var nowShowing = list.filter(":visible").length;
if (nowShowing >= numInList) {
button.hide();
}
});
});
PHP
function employeelist21($pdo)
{
$query=" sql query here";
$stmt = $pdo->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (!empty($results)) {
$data='';
$data='<ul><li>
<div class="box">
<div><span>Company</span></div>
<div><span>Industry</span></div>
<div><span>Name</span></div>
<div><span>Location</span></div>
</div>
</li>';
foreach($results as $key){
$data.='<li>
<div class="box">
<div><h4>'.$key['Industry'].'</h4></div>
<div><p>'.$key['industry_name'].'</p></div>
<div><p>'.$key['name'].'</p></div>
<div><p>'.$key['city'].'</p></div>
</div>
</li>';
}
$data.='</ul><div class="text-center">Load More</div>';
}
else{
$data.='No records available';
}
echo json_encode($data);
}
First, I would rather transfer back a list of data (not html) in json format and use that like an array, creating the HTML for it in javascript. BUT we don't always get what we want, so in this case I would assign an attribute to each set of 20 like this:
// at the top of your script (not in a function)
let perPage = 20, onGroup=0
// in your ajax function ...
success: function(data){
$('#employeelist').hide();
$('#employeelist').append(data);
$('#employeelist box').each( function(index) {
if (index===0) return; //header row
$(this).data('group',Math.floor(index-1/perPage))
});
$('#employeelist box').hide()
$('#employeelist box [data-group=0]').show()
$('#employeelist').show();
}
Then for the button, remove this from the PHP and make it an element under the results div
<div class="text-center">Load More</div>
Then in your script
$(document).ready(function() {
$("#next").click(function(){
$('#employeelist box [data-group='+onGroup+']').hide()
onGroup++;
$('#employeelist box [data-group='+onGroup+']').show()
if ($('#employeelist box [data-group='+(onGroup+1)+']').length ===0) {
$(this).hide();
}
});
});
Hard to test here, but let me know if it doesn't work
I'm trying to use ajax to store the JavaScript variables which get their values from divs into MySql every 10 seconds. But for some reason the PHP doesn't recognize the variables I'm Posting to it. It displays Undefined Index for all the variables. I tried to use the if(isset($_POST['Joy'])) and the error disappeared but the sql query is never created.
Here is the HTML code (Note: The HTML is originally provided by Affectiva (https://www.affectiva.com) for the video stream facial emotion recognition system. The code lines followed with // are from the original HTML file. The rest are personal effort to store the values of emotions to the database),
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://download.affectiva.com/js/3.2/affdex.js"></script>
</head>
<body>
<div class="container-fluid"> //
<div class="row"> //
<div class="col-md-8" id="affdex_elements" //
style="width:680px;height:480px;"></div> //
<div class="col-md-4"> //
<div style="height:25em;"> //
<strong>EMOTION TRACKING RESULTS</strong><br> //
Joy <div id="Joy"></div> //
Sad <div id="Sadness"></div> //
Disgust <div id="Disgust"></div> //
Anger <div id="Anger"></div> //
Fear <div id="Fear"></div> //
</div> //
</div> //
</div> //
</div> //
<div> //
<button id="start" onclick="onStart()">Start</button> //
</div> //
Here is the JavaScript code,
var divRoot = $("#affdex_elements")[0]; //
var width = 640; //
var height = 480; //
var faceMode = affdex.FaceDetectorMode.LARGE_FACES; //
var detector = new affdex.CameraDetector(divRoot, width, height,
faceMode); //
detector.detectAllEmotions(); //
function onStart() { //
if (detector && !detector.isRunning) { //
detector.start(); //
} } //
function log(node_name, msg) { //
$(node_name).append( msg ) //
} //
setInterval(function getElement(){
var j = Number($("#Joy").text()); //div value
var s = Number($("#Sadness").text()); //div value
var d = Number($("#Disgust").text()); //div value
var a = Number($("#Anger").text()); //div value
var f = Number($("#Fear").text()); //div value
$.ajax({
url: "HTML.php",
data: {Joy:j,Sadness:s,Disgust:d,Anger:a,Fear:f},
type: 'POST',
success : function (){
alert("sucess");
} });
}
,10000);
detector.addEventListener("onImageResultsSuccess", function(faces, image,
timestamp) { //
$("#Joy").html("");$("#Sadness").html("");$("#Disgust").html(""); //
$("#Anger").html("");$("#Fear").html(""); //
var joy = JSON.stringify(faces[0].emotions.joy,function(key,val) {
return val.toFixed ? Number(val.toFixed(0)) : val; //
});
var sad = JSON.stringify(faces[0].emotions.sadness,function(key,val) {
return val.toFixed ? Number(val.toFixed(0)) : val; //
});
var disgust =
JSON.stringify(faces[0].emotions.disgust,function(key,val) {
return val.toFixed ? Number(val.toFixed(0)) : val; //
});
var anger = JSON.stringify(faces[0].emotions.anger,function(key,val) {
return val.toFixed ? Number(val.toFixed(0)) : val; //
});
var fear = JSON.stringify(faces[0].emotions.fear,function(key,val) {
return val.toFixed ? Number(val.toFixed(0)) : val; //
});
log('#Joy', JSON.parse(joy) );
log('#Sadness', JSON.parse(sad));
log('#Disgust', JSON.parse(disgust));
log('#Anger', JSON.parse(anger));
log('#Fear', JSON.parse(fear));
});
I get the success alert but the database contain nothing. Here is my PHP code,
<?php
$conn = mysqli_connect('localhost', 'root', '', 'emotions');
if(isset($_POST['Joy'])){
$Joy = $_POST['Joy'];
$Sadness = $_POST['Sadness'];
$Disgust = $_POST['Disgust'];
$Anger = $_POST['Anger'];
$Fear = $_POST['Fear'];
$sql = "Insert into IPEMOTION (JOY, SADNESS, DISGUST, ANGER, FEAR) values
($Joy,$Sadness,$Disgust,$Anger,$Fear)";
mysqli_query($conn, $sql); }
?>
One test I have made is checking the contents of $_POST['Joy'] so I wrote the following code in my php
if (!isset($_POST['Joy'])){
echo "Joy is empty";}
after running the code the previous message "Joy is empty" appeared to me.
Your data shouldn't be like that!
From the Documentation, the data should be like this :
{variableName: value}
So, in your case, the data should be :
{Joy:Joy,Sadness:Sadness,Disgust:Disgust,Anger:Anger,Fear:Fear}
Without the quotes (')
And in HTMLNew.php you can do :
$joy = $_POST['Joy'];
I'm just gonna keep helping you through the answer section, as it is the most easy way for now. So you are saying that the ajax success alert is popping. Then i think that your Interval is not functioning well. Change this:
setInterval(function getElement(){
var j = Number($("#Joy").text()); //div value
var s = Number($("#Sadness").text()); //div value
var d = Number($("#Disgust").text()); //div value
var a = Number($("#Anger").text()); //div value
var f = Number($("#Fear").text()); //div value
$.ajax({
url: "HTML.php",
data: {Joy:j,Sadness:s,Disgust:d,Anger:a,Fear:f},
type: 'POST',
success : function (){
alert("sucess");
} });
},10000);
Into this:
function getElement(){
var j = Number($("#Joy").text()); //div value
var s = Number($("#Sadness").text()); //div value
var d = Number($("#Disgust").text()); //div value
var a = Number($("#Anger").text()); //div value
var f = Number($("#Fear").text()); //div value
$.ajax({
url: "HTML.php",
data: {Joy:j,Sadness:s,Disgust:d,Anger:a,Fear:f},
type: 'POST',
success : function (){
alert("sucess");
}
});
}
setInterval(function() {
getElement();
}, 10000);
Just a few question. To see if your values are right you can echo $Disgust in your PHP Script. Then change this:
success : function (){
alert("sucess");
}
Into this
success : function (data){
alert(data);
}
Then:
<?php
//$conn = mysqli_connect('localhost', 'root', '', 'emotions');
//if(isset($_POST['Joy'])){
$Joy = $_POST['Joy'];
$Sadness = $_POST['Sadness'];
$Disgust = $_POST['Disgust'];
$Anger = $_POST['Anger'];
$Fear = $_POST['Fear'];
echo $Joy;
echo $Sadness;
echo $Disgust;
echo $Anger;
echo $Fear;
//$sql = "Insert into IPEMOTION (JOY, SADNESS, DISGUST, ANGER, FEAR) values
//($Joy,$Sadness,$Disgust,$Anger,$Fear)";
//mysqli_query($conn, $sql);
//}
?>
Let me know. I'm deleting all my past answers until now.
Trying to use AJAX to submit form data to a PHP file. Everything in the code seems to work except for a call to the PHP file.
I setup a Java Alert() on the PHP file and it never alerts.
I am sure it is an issue with the AJAX code but I don't know it well enough to figure out what is going wrong.
The AJAX Call:
$(document).on('click','.addItem',function(){
// Add Item To Merchant
var el = this;
var id = this.id;
var splitid = id.split("_");
// Add id's
var addid = splitid[1]; // Merchant ID
var additem = splitid[2]; // Item ID
// AJAX Request
$.ajax({
url: "jquery/addItem.php",
type: "POST",
data: { mid : addid , iit : additem },
success: function(response){
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(300, function(){
$(this).remove();
});
}
});
});
The HTML Form Call Within a Table:
<span class='addItem' id='addItem_<?php echo $m; ?>_<?php echo $list['id']; ?>' >Add Item</span>
Ok Simple PHP code that it calls to with some alerts for testing:
<?php
require_once("../includes/constants.php");
require_once("../includes/functions.php");
$iid = filter_input(INPUT_POST, 'iit', FILTER_SANITIZE_STRING); // Item ID
$mid = filter_input(INPUT_POST, 'mid', FILTER_SANITIZE_STRING); // Merchant ID
$slot = 0;
$slot = getMerchSlot($mid);
?>
<script>
alert ("Slot Value: <?php echo $slot; ?>");
</script>
<?php
$result = $pdoConn->query("INSERT INTO merchantlist (merchantid, item, slot)
VALUES
('$mid', '$iid', '$slot') ");
if ($result) {
?>
<script>
alert("Looks like it worked");
</script>
<?php
}
echo 1;
?>
I am getting particular list of product items through ajax, by passing their unique id to server. Now each product has its own set of properties which I have to display on page with product image. When I set the values through jquery, only last value in the array got printed. Following are my coding files.
images.php
while($fetch = mysql_fetch_array($result))
{
?>
<div class="col-sm-4">
<div class="thumbnail">
<a class="productitemid" href="productpurchase.php?id=<?php echo $fetch['itemID'];?>"><img class="img-responsive productimage" src="uploadedfiles\<?php echo $fetch['imageURL'];?>" alt="<?php echo $fetch['imageURL'];?>" /></a>
<div class="text-center productitemname" style="font-weight:bold;"><?php echo $fetch['itemName']; ?></div>
<div class="badge col-sm-offset-1 productprice"><?php echo $fetch['price']; ?></div>
<span class="col-md-offset-7"><a class="productitemid btn btn-success" href="productpurchase.php?id=<?php echo $fetch['itemID'];?>">BUY</a></span>
</div>
</div>
<?php
}
js file
$(document).ready(function(){
$('.menProdCatgry').on('click',function(){
$.ajax({
type: "post",
url: "getselectedproducts.php",
data:{
"prodId" : $('.menProdCatgry').attr('prodCatId')
},
dataType: "json",
success: function(data){
console.log(data);
$.each(data, function(){
var getprodId = this.prodId;
var getimageURL = this.imageURL;
var getprice = this.price;
var getitemName = this.itemName;
var getitemID = this.itemID;
$('.productimage').attr('src','uploadedfiles\/'+getimageURL);
$('.productitemname').text(getitemName);
$('.productprice').text(getprice);
$('.productitemid').attr('href','productpurchase.php?id='+getitemID);
});
},
error: function(data){
console.log(data);
}
});
});
});
You can see the code of the foreach is only overwriting the values and attributes of the
$('.productimage'),
$('.productitemname')
// and so on
so you only see the last data of the response
$.each(data, function() {
var getprodId = this.prodId;
var getimageURL = this.imageURL;
var getprice = this.price;
var getitemName = this.itemName;
var getitemID = this.itemID;
// create a tag
var a = $('<a/>');
a.attr('href', 'productpurchase.php?id='+getitemID);
// create new image
var img = $('<img/>');
img.attr('src', 'uploadedfiles/'+getimageURL);
var prodname = $('<div/>')
prodname.html(getitemName);
var prodprice = $('<div/>');
prodprice.html(getprice);
// insert image to a
a.append(img);
var container = $('<div/>');
// combine them all
container.append(a);
container.append(prodname);
container.append(prodprice);
// append to document
// you can change this according to you need
// to accomplish
$('body').append(container);
});
here i created a dynamic dom element for every iteration of the foreach
then it will create a new sets of data then it will insert/include/append
to the html element
An alternative solution..
If you added some sort of identifier for each product-block, like below:
<div class="thumbnail" id="prodId<?php echo $fetch['prodId'];?>">
You could narrow the selector in your each to a specific scope:
$.each(data, function(){
var getprodId = this.prodId;
var getimageURL = this.imageURL;
var getprice = this.price;
var getitemName = this.itemName;
var getitemID = this.itemID;
var myScope = '#prodId' + getprodId;
$('.productimage', myScope).attr('src','uploadedfiles\/'+getimageURL);
$('.productitemname', myScope).text(getitemName);
$('.productprice', myScope).text(getprice);
$('.productitemid', myScope).attr('href','productpurchase.php?id='+getitemID);
});
This will make sure that only classes found within your defined scope (#prodIdX) are selected and altered.
Right now I have this code loading only 1 page (load.php?cid=1 but I want to load 5-8 (cid=1,cid=2,cid=3,cid=4,cid=5,cid=6,cid=10 ...etc )in different div(s).
how will I achieve it ?
$(document).ready(function() {
function loading_show() {
$('#loading_Paging').html("<img src='images/loading.gif'/>").fadeIn('fast');
}
function loading_hide() {
$('#loading_Paging').fadeOut 'fast');
}
function loadData(page) {
loading_show();
$.ajax({
type: "POST",
url: "load.php?cid=1",
data: "page=" + page,
success: function(msg) {
$("#container_Paging").ajaxComplete(function(event, request, settings) {
loading_hide();
$("#container_Paging").html(msg);
});
}
});
}
As JimL alluded to, I would give each element on your page a common class, give each element a unique data attribute like data-cid="1", iterate through each element grabbing the cids and calling the ajax function for each.
Id go a step further by using a promise to get all of the ajax responses then load all the data when the promise has been resolved (when all the ajax requests have been completed).
Here is a working example
The HTML:
<div id="loading_Paging"></div>
<div class="myElements" data-cid="1"></div>
<div class="myElements" data-cid="2" ></div>
<div class="myElements" data-cid="3" ></div>
<div class="myElements" data-cid="4" ></div>
<div class="myElements" data-cid="5" ></div>
<div class="myElements" data-cid="6" ></div>
<div class="myElements" data-cid="7"></div>
<div class="myElements" data-cid="8" ></div>
The jQuery:
$(function() {
var page = 'some string...'
loadData(page);
function loadData(){
$('#loading_Paging').html("<img src='images/loading.gif'/>").fadeIn('fast');
// loop through each image element
// calling the ajax function for each and storing the reponses in a `promise`
var promises = $('.myElements').map(function(index, element) {
var cid = '&&cid=' + $(this).data('cid'); // get the cid attribute
return $.ajax({
type: "POST",
url: 'load.php',
data: "page=" + page +cid, //add the cid info to the post data
success: function(msg) {
}
});
});
// once all of the ajax calls have returned, te promise is resolved
// and the below function is called
$.when.apply($, promises).then(function() {
// arguments[0][0] is first result
// arguments[1][0] is second result and so on
for (var i = 0; i < arguments.length; i++) {
$('.myElements').eq(i).html( arguments[i][0] );
}
$('#loading_Paging').fadeOut('fast');
});
}
});
The PHP I used for my example:
<?php
if (isset($_POST['cid']) ){
// this is just a contrived example
// in your code youd use the cid to
// get whatever data you need for the current div
echo 'This is returned message '.$_POST['cid'];
}
?>