ajax call returns only last id - php

I am trying to develop an add to cart function via ajax, the problem is that no matter which product I add to cart, it adds the last item on the list and then increments the same product upon clicking on any other product. Here is my code:-
<?php
$i = 1;
while($row = mysqli_fetch_array($run_products)){
$op_id = $row['option_id'];
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row['option_desc'] . "</td>";
echo "<td>
<form action='' method='post' class='p_form'>
<input type='text' name='product_id' value='$op_id' pid='$op_id'>
<input type='text' name='quantity' value='1' pid='$op_id'>
<input class='btn btn-primary add' type='submit' name='add_to_cart' value='Add to Cart' id='product' pid='$op_id'>
</form>
</td>";
echo "</tr>";
$i++;
}
?>
Here is jquery:
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.p_form',function (event) {
event.preventDefault();
var element = $(this);
var id = element.attr("pid");
//alert(id);
$.ajax({
url: 'action.php',
method: 'post',
//data: {id:id},
data:$('.p_form').serialize(),
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>
Here is action.php, the $product_id always returns as 4 (for example) if the last id in the last is 4
if (!empty($_POST)){
$product_id = $_POST['product_id'];
echo $product_id;
}

Need to do it like below:-
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.add',function (event) {//instead of form click add event on form button click
event.preventDefault();
var element = $(this);
var id = element.attr("pid");
//alert(id);
$.ajax({
url: 'action.php',
method: 'post',
data:element.parent('.p_form').serialize(), //serialize clicked button parent form
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>

Trigger click event on button click not on the form click:
This will work for you for each product.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.add',function (event) {
event.preventDefault();
var element = $(this);
var id = element.attr("pid");
//alert(id);
$.ajax({
url: 'action.php',
method: 'post',
data: {id:id}, //send id of product you wish to add
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>
And on server side:
if (!empty($_POST)){
$product_id = $_POST['id'];//get only that id posted in ajax call
echo $product_id;
}

Related

how to insert data with ajax and php without page refresh

I real need your help since I'm a beginner in php and Ajax. My problem is that, I can not send data in the database via my appended form in post.php, also when the button of id #reply clicked it sends empty data to database by refreshing the page. When the reply link is pressed I only get the Result of reply link to be shown without other information (name and comment). I need your help to make my appanded form to be able to add/send data to the database without refreshing the page, I also need to disable the form from index.php to make replies when the reply button / link is pressed. Thank you.
post.php
<?php include("config.php"); //inserting
$action=$_POST["action"];
if($action=="addcomment"){
$author = $_POST['name'];
$comment_body = $_POST['comment_body'];
$parent_id = $_POST['parent_id'];
$q = "INSERT INTO nested (author, comment, parent_id) VALUES ('$author', '$comment_body', $parent_id)";
$r = mysqli_query($conn, $q);
if(mysqli_affected_rows($conn)==1) { header("location:index.php");}
else { }
}
// showing data
error_reporting( ~E_NOTICE );
function getComments($conn, $row) {
$action=$_POST["action"];
if($action=="showcomment"){ $id = $row['id'];
echo "<li class='comment'><div class='aut'>".$row['author']."</div><div class='comment-body'>".$row['comment']."</div>";
echo "<a href='#comment_fo' class='reply' id='".$row['id']."'>Reply</a>";
$result = mysqli_query($conn, "SELECT * FROM `nested` WHERE parent_id = '$id' ORDER BY `id` DESC");
}
if(mysqli_num_rows($result)>0) { echo "<ul>";
while($row = mysqli_fetch_assoc($result)) { getComments($conn,$row); }
echo "</ul>"; } echo "</li>";
}
if($action=="showcomment"){
$q = "SELECT * FROM nested WHERE parent_id = '".$row['id']."' ORDER BY `id` DESC";
$r = mysqli_query($conn, $q);
while($row = mysqli_fetch_assoc($r)){ getComments($conn,$row); }
}
?>
<!DOCTYPE HTML><head><script type='text/javascript'>
$(document).ready(function(){
$("a.reply").one("click", function() {
var id = $(this).attr("id");
var parent = $(this).parent();
$("#parent_id").attr("value", id);
parent.append(" <br /><div id='form'><form><input type='text' name='name' id='name'><textarea name='comment_body' id='comment_body'></textarea><input type='hidden' name='parent_id' id='parent_id' value='0'><button id='reply'>Reply</button></form></div>");
$("#reply").click(function(){
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){ showComment(); }
});
});
});
});
</script></head></html>
//index.php
<html><head><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function showComment(){
$.ajax({
type:"post",
url:"post.php",
data:"action=showcomment",
success:function(data){ $("#comment").html(data); }
});
}
showComment();
$(document).ready(function(){
$("#button").click(function(){
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){
showComment();
}
});
});
});
</script></head><body>
<form id="form_comment">
<input type="text" name="name" id='name'/>
<textarea name="comment_body" id='comment_body'></textarea>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
<input type="button" id="button" value="Comment"/>
</form>
<div id="comment"></div> </body></html>
$(document).ready(function(){
$("#button").click(function(e){
e.preventDefault(); //add this line to prevent reload
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){
showComment();
}
});
});
});
Here is a simple incomplete ajax example.
FromPage.php
Here is the ajax that I'd use. The variables can be set however you like.
<script type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
var name = "John Smith";
$.ajax({
url: 'toDB.php',
type: 'post',
dataType: 'html',
data: {
carArray: cars,
firstName: name
},
success: function(data) {
console.log(data); //Testing
}
});
</script>
toDB.ph
This is the second page - the one that writes the values to the database etc.
<?php
$cars = $_POST['carArray'];
$FirstName=$_POST['firstName'];
//Used to test - it will print out the array
print("<pre>");
print_r($cars);
print("</pre>");
//Do something with $cars array and $FirstName variable
?>

AJAX Submit Button Got Disabled

i want to create a dynamic search using php and ajax, and then choose the results that will be inserted in another tabke in database by using checkboxes..
here's the code to query the search in table
<?php
//include('../koneksi/koneksi.php');
mysql_connect('localhost','root',''); //ini untuk koneksi databasenya
mysql_select_db('aam'); // nama tabel
$key=$_GET['q'];
$query = mysql_query("select * from dokter where nama LIKE '%$key%'");
echo "
<table border='1'>
<tr>
<th>Kode Dokter</th>
<th>Nama</th>
<th>Spesialis</th>
<th>Alamat</th>
<th>Kota</th>
<th>Pilih</th>
</tr>
";
while($row = mysql_fetch_array($query))
{
//$array[] = $row['title'];
echo "<tr>";
echo "<th>" . $row['id_dokter'] . "</th>";
echo "<th>" . $row['nama'] . "</th>";
echo "<th>" . $row['spesialis'] . "</th>";
echo "<th>" . $row['alamat'] . "</th>";
echo "<th>" . $row['kota'] . "</th>";
echo"<th> <input name='chkbox[]' type='checkbox' value='". $row['id_dokter'] ."'> </th>";
echo "</tr>";
}
echo "</table>";
?>
the code above will generate a table in my page. after the results populated, i use this code to submit my choices to the database
function kirimJadwal(){
$(document).ready(function(e) {
var checkboxdokter = new Array();
$("form#formulir").on('submit', function(e){
e.preventDefault();
/*$("input:checked").each(function() {
checkboxdokter.push($(this).val());
});*/
$.ajax({
type: "POST",
url: "Planning-kirim.php",
dataType:"html",
//data: {checkboxdokter:checkboxdokter},
data: $("form#formulir").serialize(),
success: function(data){
alert(checkboxdokter);
}
});
});
});
}
and this is the form that i use to put the results
<form method='post' action='Planning-kirim.php' name="formulir" id="formulir">
</div>
<label> Atur Jadwal</label>
<a id="dt1" href="#" <span class="glyphicon glyphicon-calendar" aria-hidden="true"></span></a>
<input type="date" name="date">
<input type="submit" id="kirim" value="Submit" />
</form>
the problem is, when the results populated, the submit button will do nothing everytime i click it? is there any of my functions here that freezes the button???
Try to replace your javascript with this:
$(document).ready(function() {
$("#formulir").on('submit', function(){
$.ajax({
type: "POST",
url: "Planning-kirim.php",
dataType:"html",
data: $("#formulir").serialize(),
success: function(data){
alert("123");
}
});
return false;
});
});
And html with this:
$(document).ready(function() {
$("#formulir").on('submit', function(){
$.ajax({
type: "POST",
url: "Planning-kirim.php",
dataType:"html",
data: $("#formulir").serialize(),
success: function(data){
alert("123");
}
}).done(function(){
alert();
});
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method='post' action='Planning-kirim.php' name="formulir" id="formulir">
<label> Atur Jadwal</label>
<a id="dt1" href="#" ><span class="glyphicon glyphicon-calendar" aria-hidden="true"></span></a>
<input type="date" name="date">
<input type="submit" id="kirim" value="Submit" />
</form>
Click on the submit button and look to the firebug. You'll find sent requests there. So the javascript works.
Document need to load before function.
$(document).ready(function(e) {
kirimJadwal();
function kirimJadwal(){
var checkboxdokter = new Array();
$("form#formulir").on('submit', function(e){
e.preventDefault();
/*$("input:checked").each(function() {
checkboxdokter.push($(this).val());
});*/
$.ajax({
type: "POST",
url: "Planning-kirim.php",
dataType:"html",
//data: {checkboxdokter:checkboxdokter},
data: $("form#formulir").serialize(),
success: function(data){
alert(checkboxdokter);
}
});
});
});
}

JQuery Function not response inside of php while loop

here i want to passing the product_id value into addcart.php file through the jQuery Function.here 'Add Cart' button generated dynamically by php while loop. every button set as a invidual product id, there is fine until this..
what's my problem is All Button pass the same value to addcart.php file when i clicked each one...i want to pass the value of individual one(button)..
Please Give me a Solution... addcart.php just contain code like
"echo $_POST['pid']; only"
<?php
include('includes/db-config.php');
$shop_id=$_GET['sid'];
$get_product_q = mysql_query("select product from shops where sid = $shop_id");
$get_product_f = mysql_fetch_array($get_product_q);
$product_id = explode(',', $get_product_f['product']);
$count_product_id = count($product_id);
for($i=0;$i<$count_product_id;$i++){
$get_product_q = mysql_query("select * from products where pid = $i");
$get_product_f = mysql_fetch_array($get_product_q);
$product_id = $get_product_f['pid'];
?>
<script>
$(document).ready(function(){
$('.but').click(function(){
$.ajax({
type: 'POST',
url:"addcart.php",
data : { pid : '<?php echo $product_id?>'},
success:function(result){
$("#div1").html(result);
}});
});
});
</script>
<?php
$product_name = $get_product_f['name'];
$product_description = $get_product_f['description'];
$product_price = $get_product_f['price'];
echo $product_name;
echo '<br>';
echo $product_description;
echo '<br>';
echo $product_price;
echo '<br>';
echo '<input class="but" type="button" value="Add Cart" />';
echo '<br><br>';
}
?>
<div id="div1"></div>
You are repeating the entire Javascript for every product. Move the Javascript out of the loop and set the product ID as a data-productid attribute on the button:
echo '<input class="but" type="button" value="Add Cart" data-productid="' . htmlspecialchars($product_id) . '" />';
Then when you make the ajax call (on click), read the product ID and set it as the POST data:
$.ajax({
type: 'POST',
url:"addcart.php",
data : { pid : $(this).data('productid') },
success:function(result){
$("#div1").html(result);
}
});
Try this :
replace : echo '<input class="but" type="button" value="Add Cart" />'; by this : echo '<input class="but" type="button" rel="'.htmlspecialchars($product_id).'" value="Add Cart" />';
and your script :
<script>
$(document).ready(function(){
$('.but').click(function(){
$.ajax({
type: 'POST',
url:"addcart.php",
data : { pid : $(this).attr('rel'),
success:function(result){
$("#div1").html(result);
}});
});
});
</script>
The problem is that you're binding it to a click on all elements with the class ".but", if you on the other hand gave the button an id like
echo '<input data-pid="'. sha1($product_id) . '" class="but" type="button" value="Add Cart" />';
and then in your jquery function would do the following (outside the loop):
<script>
$(document).ready(function(){
$('.but').click(function(){
$.ajax({
type: 'POST',
url:"addcart.php",
data : $(this).data(),
success:function(result){
$("#div1").html(result);
}
});
});
});
</script>
Then you would get around the problem, as it then listens for the click event on each element, but the data is varying on each element.
I hope this helps.
in you loop ,.but was bind an function each time,so the last bind one works .try to give the .but elements an unique id such as "id=$product_id";
and you can bind the function once (outside the loop).this simply like:
$(document).ready(function(){
$('.but').click(function(){
var data = $(this).attr("id");
$.ajax({
type: 'POST',
url:"addcart.php",
data : { pid : data},
success:function(result){
$("#div1").html(result);
}});
});
});
be lucky.

How to submit inline edit with ajax?

How can I submit this form with ajax.
Right now it creates a table from mysql query. When you click the Edit button behind a row, Javascript makes all the cells to input=text.
Now when you click the Submit button at the end of the line I would like it to submit edited data to mysql via ajax.
I don't understand where do I get the data that I need to POST with ajax.
<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.9.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.qtip-1.0.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".edit").click(function(){
var tr = $(this).closest("tr");
var submit = "<input type='submit' name='Submit' value='Submit' />";
tr.find(".td").each(function(){
var name = $(this).attr("title");
var value = $(this).html();
var input = "<input type='text' name='"+name+"' value='"+value+"' />";
$(this).html(input);
});
tr.find(".button").html(submit);
});
});
// this is the id of the submit button
$(".button").click(function() {
$.ajax({
type: "POST",
url: "index.php?page=update_mysql",
data: $("#change").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
<form id="change" method="post" action="#">
<table>
<?PHP
$sql="SELECT * FROM names";
$result = mysql_query($sql)or die(mysql_error());
WHILE ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr class="row">';
echo '<td class="td" title="id">'.$row["id"].'</td>';
echo '<td class="td" title="first_name">'.$row["first_name"].'</td>';
echo '<td class="td" title="last_name">'.$row["last_name"].'</td>';
echo '<td class="button" title="button"><button class="edit">Edit</button></td>';
echo '</tr>';
}
?>
</table>
</form>
And update_mysql.php looks like this:
<?php
include 'firewall.php';
if ($_POST['Submit'] == "Submit") {
$id = $_POST['id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$sql_edit = "UPDATE names SET first_name = '$first_name', last_name = '$last_name' WHERE id = '$id'";
$result_edit = mysql_query($sql_edit) or die(mysql_error());
}
?>
Try this.
$(document).ready(function(){
$(".edit").click(function(){
var tr = $(this).closest("tr");
tr.find(".td").each(function(){
var name = $(this).attr("title");
var value = $(this).html();
var input = "<input type='text' name='"+name+"' value='"+value+"' />";
$(this).html(input);
});
var submit = "<input type='button' name='Submit' value='Submit' />";
tr.find(".button").html(submit);
});
});
$(".button input[type=button]").live('click', function() {
var data = $('form#change').serialize();
// post data using ajax
$.ajax({
type: "POST",
url: "index.php?page=update_mysql",
data: data,
success: function(data) {
alert(data); // show response from the php script.
}
});
});
NOTE: I have changed the "type" attribute of submit button to "type='button'". That will not fire default submit of browser. The same button is bound to collect form data and submit using ajax.
Happy Coding.
EDIT:
It takes you to "index.php?page=my_page#" coz form is submitted whey you click the <input type="submit">. Haven't you changed it to <input type="button"> yet? You don't need a submit button when its not there to submit the form. There are other non-submit button to bind javascript handlers to.
You can use jquery.serialize():
var data = $('form').serialize();

Return data from PHP back to a javascript file?

I have a comments section on my websites that uses jQuery to animate comments in without reloading the page, as well as deleting comments.
Right now, I have it so when you write a comment, it sends it to a external JS, then to a php file where it processes. If it was successful, it will append the comment into the comment section. My delete action: jQuery deletes my the comment ID in the mysql database.
So my issue is I want to add a delete button via jQuery and somehow call back to the javascript file and tell it the id so the delete button knows the ID to put in the form so the delete file knows what to delete?
Here's my add_comment script:
$(function() {
$(".commentbutton").click(function() {
$.ajax({
type: "POST",
url: "http://myflashpics.com/process_addcomment.php",
data: $("#commentform").serialize(),
success: function() {
var theComment = $("#commentsss").val();
var theUserId = $("#user_id_two").val();
var thePhotoId = $("#photo_id").val();
var theProfilePicture = $("#user_profile_picture").val();
var theUsername = $("#user_username").val();
// Get new HTML data
var html = "<div class='comment_odd'><img src='" + theProfilePicture + "' class='comment_thumbnail'/><div class='comment_username'>" + theUsername + "</div><div class='comment_text'>" + theComment + "</div></div>";
// Append, then fade in
$(html).hide().appendTo(thecommentsdisplay).fadeIn(500);
}
});
return false;
});
});
Thanks in advance!Coulton
EDIT 1:
Here's my comments form (just to clarify):
user_id_two (the user's ID)
commentsss (comments field)
photo_id (the id of the photo being commented on)
user_profile_picture (profile to display on the user's profile picture in the banner)
user_username (username of the user commenting)
Here's also my delete button form:
<form method='post' action='' name='deleteform' id='deleteform'>
<input type='hidden' name='userid' value='<?php echo "$userid_session"; ?>' />
<input type='hidden' name='userpass' value='<?php echo "$password_session"; ?>' />
<input type='hidden' name='pictureid' id='pictureid' value='<?php echo "$picture_id"; ?>' />
<input type='hidden' name='profilepictureid' id='profilepictureid' value='<?php echo "$user_profile_picture_id"; ?>' />
</form>
And lastly my DELETE COMMENT jQuery:
$(function() {
$(".commentdeletebutton").click(function() {
var className = $(this).attr('class');
var theID = className.replace(/delete_button commentdeletebutton delete_(\d+)/, "$1");
commentDone = "#comment_" + theID;
formDone = "#commentdeleteform_" + theID;
$.ajax({
type: "POST",
url: "http://myflashpics.com/process_deletecomment.php",
data: $(formDone).serialize(),
success: function() {
$(commentDone).hide();
}
});
return false;
});
});
If you add an link for deleting, you can insert the complete url for deleting in the href, i.e. http://myflashpics.com/process_removecomment.php?id=xx.
So, you can bind a click event to that link and get the right url using $(this).attr('href') and doing the delete using ajax.
Edited for a more complete sample:
<? [[Loop your recordset]] { ?>
<div class="comment">
Delete
<div class="comment">
[[Comment content...]]
</div>
</div>
<? } ?>
<script>
$(function() {
$(".commentdeletebutton").click(function() {
$this = $(this);
$.ajax({
url: $this.attr('href'),
success: function(data) {
$this.parent().slideUp('fast', function() {
$this.parent().remove();
});
}
});
return false;
});
});
</script>

Categories