set values from jquery array of objects php? - php

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.

Related

Ajax post work but PHP doesn't recognize it

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.

AJAX Form Submission Not Querying PHP

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;
?>

how to pass many variable with tag <a>?

I want to pass on three variables using tag <a> and jquery, I pass two variables using the name and identifier and the class. I tried to use the value in tag <a> But it did not work.
this is tag <a>:
<a href="#inserts" class="add_result"
id="<?php echo $row1['id_visits'];?>"
name="<?php echo $id_patient;?>"
value="<?php echo $row1['id_testing'];?>">اضافة نتائج</a>
this is jquery
$( "a.add_result" ).click(function() {
var id_visits1 = $(this).id;
var id_patient1 = $(this).name;
var id_testing1 = $(this).value;
$.ajax({
type: "POST",
url: "result_form.php",
data: { id_visits:id_visits1,id_patient:id_patient1,id_testing:id_testing1 }
});
Any idea to help me?
For validity and safety of your code use data--attributes:
Jquery has a data() function which helps to get data-attributes values:
$( "a.add_result" ).click(function() {
var id_visits1 = $(this).data("id");
var id_patient1 = $(this).data("name");
var id_testing1 = $(this).data("value");
You can also use an onClick event. The code below is working.
اضافة نتائج
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
function clickMe(element){
var id = $(element).attr('id');
var name = $(element).attr('name');
var val = $(element).attr('value');
alert(id+' : '+name+' : '+val);
}
</script>
This is helpful if you want to get the value of the certain attribute or attributes of any element.

echo data into drop list using AJAX

I have this code, where when I click on a value in my first drop list, I need to get new data from MySQL into my second drop list according to my selection.
I have this code here:
$('#sale_type').change(function() {
// get the form information
// this can be done in many ways but we are going to put the form
// data into a data object
var formData = {
'selectedValue' : $('#sale_type').val()
};
// send the data via Ajax
$.ajax({
type : 'POST', // the method we want to use to send the data
url : 'getTypeDetails.php', // the url where we want to
// send the data
data : formData, // the data object we created
dataType : 'json', // what type of data we want to get back
encode : true
})
// execute function when data has been sent and server
// code is processed
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
});
});
});
And here is getTypeDetails.php:
<?php
require_once('../include/global.php');
$data = $_POST['selectedValue'];
// Connect to database
// Use the data to get the new information
$query = "SELECT * FROM purchases WHERE sale_type = :data";
// MySQL
$results = $conn->prepare($query);
$results->bindValue(":data", $data);
$exec = $results->execute();
$res = $results->fetchAll();
$data = array();
$i = 0;
foreach($res as $row){
$data[i] = $row['sale_details'];
$i++;
}
echo json_encode($data);
?>
the problem is that I can't get the $data[i] into my new drop list with an id=sale_details
So I don't know what to put here:
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
});
EDIT
Those are my HTML drop lists:
<label for="sale_type" class="col-lg-1 control-label" style="float:right">النوع</label>
<select id="sale_type" name="sale_type" class="dropdown-header" style="float:right">
<option value="undefined">اختر</option>
<?php
foreach($fetchType as $ft){ ?>
<option value="<?php echo $ft['sale_type'] ?>"><?php echo $ft['sale_type'] ?></option>
<?php } ?>
</select>
<label for="sale_details" class="col-lg-1 control-label" style="float:right">الصنف</label>
<select id="sale_details" name="sale_details" class="dropdown-header" style="float:right">
</select>
It should be something like this:
.done(function(data) {
var secondDropdown = $("#second-dropdown");
secondDropdown.empty();
$.each(data, function(index, value) {
secondDropdown.append("<option>" + value + "</option>");
});
return;
}
Replace your js code with my code
<script>
$(document).ready(function() {
$('#sale_type').change(function() {
var formData = { 'selectedValue' : $( "#sale_type option:selected" ).val() };
console.log(formData);
$.ajax({
type: 'POST',
url: 'getTypeDetails.php',
data: formData,
success: function(data){
var obj = jQuery.parseJSON(data);
var secondDropdown = $("#sale_details");
secondDropdown.html('');
for (var prop in obj) {
secondDropdown.append("<option>" + obj[prop] + "</option>");
}
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
});
});
</script>
and add jquery link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
in your <head> tag

how to use each on ajax using onclick

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

Categories