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;
?>
Related
I create a load more button for load more posts from the database but when I add like button for that if one time clicks on load more button and then click on the like button, like.php file runs two times and adds two lines in likes table. if I click 2 times on load more then like.php file runs 3 times and...
I want to know how I should create a loadmore button and like the button to works fine.
this is simple of my codes:
posts.php :
<div id="comnts2"></div>
<button id="btn2" >load more</button><script>
$(document).ready(function() {
var comco2 = 2;
var offset2 = 0;
$("#btn2").click(function() {
$.ajax({
method: "POST",
url: "ld_comco.php",
data: { comnco2 : comco2, offset2 : offset2}
})
.done(function(msg2) {
$("#btn2").hide();
} else {
$("#comnts2").append(msg2);
});
offset2 = offset2 + comco2;
});
$("#btn2").trigger("click");
});
</script>
ld_comco.php:
<?php
$comnco2=$_POST['comnco2'];
$offset2=$_POST['offset2'];
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid = '$uid' ORDER BY id DESC limit $offset2, $comnco2");
while($rp=mysqli_fetch_assoc($rzp)){
$sid=$rz['id'];
$lik=$rz['lik'];
echo $sid."<br>";
/*like*/
echo'<img class="li_ik1" data-id="'.$sid.'" src="pc3/up.png">'.$lik.' Likes</img>';
?>
</span>
<?php }?>
<script type="text/javascript">
$(document).ready(function() {
var uid=<?php echo $uid;?>;
$(document).on("click", ".li_ik1", function() {
var psid = $(this).data('id');
$.ajax({
method: "POST",
url: "like.php",
data: {psid: psid, uid: uid}
}).done();
});
});
</script>
like.php:
<?php
$id=$_POST['psid'];
$uid=$_POST['uid'];
$Y=mysqli_query($conn,"INSERT INTO `t_plik` (pid,uid) VALUES ('$id','$uid')");
$Q=mysqli_query($conn,"UPDATE `tbl_users_posts` SET lik=lik+1 WHERE id='$id'");
?>
thanks
I think the problem is, that you bind your like button multiple times globally. Each time you load the content from ld_comco.php you also call $(document).on("click", ".li_ik1", ...) in the $(document).ready block, which means you bind all ".li_ik1" buttons on the entire document (but some of them has already been bind).
I would remove the $(document).ready(...) block from the ld_comco.php and move the logic into the posts.php right before you render your content. A further positive aspect is you have your business logic at one place.
KEEP IN MIND: You get a response of buttons in msg2, thats why you do not need to filter $msg2 anymore. But if you wrap your buttons with further html tags in ld_comco.php, your buttons will be on a deeper level, so you need to use a selector again, like you did with .on("click", ".li_ik1", ...).
posts.php
...
var $msg2 = $(msg2);
// Now you bind only the loaded buttons instead of
// the buttons in the entire document for multiple times
$msg2.on("click", function() {
var $element = $(this);
var psid = $element.data('id');
var uid = $element.data('uid');
$.ajax({
method: "POST",
url: "like.php",
data: {psid: psid, uid: uid}
}).done();
});
$("#comnts2").append($msg2);
...
In your ld_comco.php you need to add the data-uid="'.$uid.'" and remove the script block. Then your file should look like this:
<?php
$comnco2=$_POST['comnco2'];
$offset2=$_POST['offset2'];
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid = '$uid' ORDER BY id DESC limit $offset2, $comnco2");
while($rp=mysqli_fetch_assoc($rzp)){
$sid=$rz['id'];
$lik=$rz['lik'];
echo $sid."<br>";
/*like*/
echo'<img class="li_ik1" data-id="'.$sid.'" data-uid="'.$uid.'" src="pc3/up.png">'.$lik.' Likes</img>';
}
?>
$("#btn2").trigger("click");
this in posts.php means click the #btn2
so after clicking it, you click it again
$(document).ready(function() {
var comco2 = 2;
var offset2 = 0;
$("#btn2").click(function() {
$.ajax({
method: "POST",
url: "ld_comco.php",
data: { comnco2 : comco2, offset2 : offset2}
})
.done(function(msg2) {
$("#btn2").hide();
} else {
$("#comnts2").append(msg2);
});
offset2 = offset2 + comco2;
});
$("#btn2").trigger("click");
});
</script>
Similarly as in PHP Ajax add to cart not working my add to cart is also not working. I am trying to show the added product name, price, quantity and total price in <div id="mycart"> here </div> but it's not working and I am not getting any errors in console. Things that do work:
I get the success alert: Product has been added to cart
but it doesn't show up in my div.
Can anyone tell me what I am doing wrong?
My form on products.php
<form class="form-item" method="post" action="?action=add&id=<?php echo $row["id"]; ?>">
bla bla input
<input type="submit" name="add_to_cart" class="btn btn-outline-secondary btn-sm" value="Add to cart">
My ajax.js
<script>
$('.form-item').on('submit', function() {
var id = $(this).attr("id");
var titel = $('#titel' + id).val();
var price = $('#price' + id).val();
var quantity = $('#quantity' + id).val();
$.ajax({
url:"cart-process.php",
method:"POST",
dataType:"json",
data:{
id:id,
titel:titel,
price:price,
quantity:quantity,
},
success:function(data)
{
$('#mycart').html(data);
alert("Product has been added to cart");
}
});
return false;
});
</script>
and my cart-process.php
<?php
session_start();
if(!empty($_SESSION['shopping_cart'])){
$total = 0;
foreach($_SESSION['shopping_cart'] as $key => $row){
$output .='<i class="ti ti-close"></i>';
$output .='<span>'.$row['titel'].'</span><span class="text-muted"> x '.$row['quantity'].'</span><br /> ';
$total = $total + ($row['quantity'] * $row['prijs']);
}
$output.='<br />Totaal:€ '.number_format($total, 2).'';
if (isset($_SESSION['shopping_cart'])){
if (count($_SESSION['shopping_cart']) > 0){
$output.='Cash payment';
$output.='Paypal payment';
}}
}
echo json_encode($output);
?>
You need to make two changes, first, tell your ajax function that you expect to receive html response:
$.ajax({
url:"cart-process.php",
method:"POST",
dataType:"html",
...
Second, do not try to json encode the PHP output, it is not json:
echo $output; // not json_encode($output);
I see it may be 3 problems
Ajax Call
$.ajax({
url:"cart-process.php", // script location
method:"POST", // if you use post, then get the values from $_POST
//dataType:"json", NO NEED
data:{
id:id, // this is how the array will be read
titel:titel,
price:price,
quantity:quantity,
},
success:function(data) //success call
{
$('#mycart').html(data);
alert("Product has been added to cart"); // even if no data is returned
//alert will be shown
}
});
return false;
Your are posting with an ajax/js script
Must obtain the variables from the $_POST array on server side, but on the server side i dont see when you are adding new product to your chart.
If you are saving the new product to the session
//as the var names on your js script will be preserved on php side
// you can just add it, if you dont needd to process this info
$_SESSION["shoping_cart"][] = $_POST;
//Now you use a loop to build the html
And here is where the third problem shows, your ajax call expects a JSON response and, php json_encoding the html response? no need, just echo $html; and on your js data = $html after the succesfull call, then add the html to the element,
$("#elementid .orclass").html(data)
Hope my answer helps you.
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.
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
I'm working on a PHP application i want to submit form without refresh page. Actually, i want my php code to be written on the same page as the one containing html and jquery code.
In order to submit form using jquery i've written this code
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
$.post("php-opt.php", //Required URL of the page on server
{ // Data Sending With Request To Server
selectrefuser:vname,
},
function(response,status){ // Required Callback Function
//alert("*----Received Data----*\n\nResponse : " + response+"\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
});
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
//return false;
//e.preventDefault();
//$("#monbutton:hidden").trigger('click');
});
});
and my php code is :
<?php
$resclient_alt = 1;
$resclient_long = 1;
if(isset($_POST['selectrefuser'])){
$client = $_POST['selectrefuser'];
echo $client;
$client_valide = mysql_real_escape_string($client);
$dbprotect = mysql_connect("localhost", "root", "") ;
$query_alt= "SELECT altitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1_alt=mysql_query($query_alt, $dbprotect);
$row_ss_alt = mysql_fetch_row($query_resclient1_alt);
$resclient_alt = $row_ss_alt[0];
//echo $resclient_alt;
$query_gps= "SELECT longitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1=mysql_query($query_gps, $dbprotect);
$row_ss_ad = mysql_fetch_row($query_resclient1);
$resclient_long = $row_ss_ad[0];
}
?>
My form is as below
<form id="form1" name="form1" method="post" >
<label>
<select name="selectrefuser" id="selectrefuser">
<?php
$array1_refuser = array();
while (list($key,$value) = each($array_facture_client_refuser)) {
$array1_refuser[$key] = $value;
?>
<option value="0" selected="selected"></option>
<option value="<?php echo $value["client"];?>"> <?php echo $value["client"];?></option>
<?php
}
?>
</select>
</label>
<button id="btn">Send Data</button>
</form>
My code does these actions:
select client get its GPS coordinates
recuperates them in php variable
use them as jquery variable
display marquer on map
So since i do this steps for many clients i don't want my page to refresh.
When i add return false or e.preventDefault the marquer is not displayed, when i remove it the page refresh i can get my marquer but i'll lost it when selecting another client.
is there a way to do this ?
EDIT
I've tried using this code, php_query.php is my current page , but the page still refresh.
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Edit
When adding e.preventDfault , this code doesn't seem to work
$( "#monbutton" ).click(function() {
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
$('#myResults').html("je suis "+php_long);
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
});
This code recuperate this value var vname = $("#selectrefuser").val(); get result from sql query and return it to jquery .
It will refresh since you have not prvent default action of <button> in script
$("#btn").click(function(e){ //pass event
e.preventDefault(); //this will prevent from refresh
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Updated
Actually, i want my php code to be written on the same page as the one containing html and jquery code
You can detect the ajax call on php using below snippet
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special code here */
}