Loop through submit buttons and post to MySQL w/ ajax - php

I currently have a form(s) that gets created based on the number of rows in the DB. Each row gets pulled in to its own form where data is editable. Each row also has it's own button.
$i = 0;
while($row = mysql_fetch_array( $result )) {
if ($row['stage']=='1'){ $i++;
<form method="post" name="form<?php echo $i;?>' id='form<?php echo $i;?>">
<input type="text" name="product<?php echo $i;?>" value="<?php echo $row['product'];?>" id="product<?php echo $i;?>" />
<input type='button' name='submit<?php echo $i;?>' value='NEXT'/>
</form>
JQUERY
$(".submit1").click(function(){
$.ajax({
type: "post",
url: "xx1.php",
data: $("#form1").serialize(),
success: function() {
alert("UPDATE SUCCESS");
location.reload();
},
error: function () {
alert("FAILED");
}
});
});
xx1.php
$ProductOne= strip_tags($_POST['product1']);
if ($StageOne == "1"){
SQL STATEMENT
}elseif ($StageOne == "2"){
SQL STATEMENT
}elseif ($StageOne == "3"){
I currently have xx.php for each row (xx1.php,xx2.php,xx3.php) and in my php file my $_POST['x'] matches the xx.php ($_POST['product1'], $_POST['product2'], $_POST['product3']
How do write something that says if submitx is clicked update that row where i = i (update product1 when submit1 is clicked, update product2 when submit2 is clicked)

You need to get button id (the one which got clicked) and call the respective file for the execution.
$("button").click(function() {
//extract the name of the button clicked
var name = $(this).attr('name');
//get the button id from name.
var buttonId = name.split('submit')[1];
$.ajax({
type: "post",
url: "xx.php",
data: $("#form" + buttonId + "").serialize(),
success: function() {
alert("UPDATE SUCCESS");
location.reload();
},
error: function () {
alert("FAILED");
}
});
});
data sent to xx.php has the id. So you may use this id to operate on xx.php.
$id = //get the id from form data sent from js
$Product = strip_tags($_POST["product{$id}"]);
.
.
//use id instead of number in further operations.

Related

Success message displaying on the wrong page

I am new to Ajax and I am trying CRUD operations using the same. I have an index.php page where I can insert and display data, also I have links to update and delete data over there.Create, Read, Update are working fine. Now the problem is that when I click the link to Delete, I am successfully sending the id to the delete_back.php and the value is getting deleted but the success message which should be printed on the index.php as I have a div named #delete_msg over there but somehow the success message is being printed on delete_back.php.
index.php
<div id="delete_msg"></div>
select_back.php
<?php
include("config.php");
$data=mysqli_query($con,"select * from student");
$col=mysqli_num_fields($data);
echo "<table>";
while($row=mysqli_fetch_array($data))
{
echo "<tr>";
for($i=0;$i<$col;$i++)
{
echo "<td>".$row[$i]."</td>";
}
echo "<td><a href='update_front.php?id=$row[0]&nm=$row[1]&add=$row[2]&cont=$row[3]'> Update </a></td>";
echo "<td><a class='delete' href='delete_back.php?id=$row[0]'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
?>
delete_back.php
<?php
$id=$_GET['id'];
include("config.php");
$data=mysqli_query($con,"delete from student where id='$id'");
if($data=="true")
{
echo "Data Deleted";
}
else
{
echo "Delete Error";
}
?>
ajax file
$(".delete").click(function(event){
event.preventDefault();
$.ajax({
url:"delete_back.php",
dataType:"html",
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
})
})
add data-id attribute to anchor tag:
echo "<td><a id='delete' data-id='".$row[0]."' href='#'>Delete</a></td>";
You can do in your ajax be like:
$("#delete").click(function(event){
var obj = $(this); // first store $(this) in obj
var id = $(this).data('id'); // get id of data using this
$.ajax({
url:"delete_back.php",
dataType:"html",
data: { id: id },
type: "Post",
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
})
})
in your php file:
$id=$_POST['id'];
First of all, I really hope you don't have a loop which prints multiple anchors with same ID...
That said, according to your html, your JS should be like the followin, otherwise you will lose your id value:
$("#delete").click(function(event){
event.preventDefault();
var my_href = $(this).attr('href');
$.ajax({
url: my_href,
dataType:"html",
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
});
return false;
});
But this isn't a really nice coding style.. I would suggest to use html5 data- attribute to store your id value
echo "<td><a id='delete' data-id='".$row[0]."' href='#'>Delete</a></td>";
You can also use javascript:; instead of # if you don't want your url to change..
And your JS should be like:
$("#delete").click(function(event){
// you can avoid preventing default behaviour because your anchor doesn't have any href value
var del_id= $(this).data('id');
$.ajax({
url: "delete_back.php",
dataType:"html",
data: {id: del_id} // use object for better reading
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
});
});
I also suggest you to check .done() construct LINK and deferred.done()
I believe that the delete link is coming from a loop containing other delete links too. If so, this is what you should do.
echo '<td><a class="lnk-delete" href="#" data-id="'.$row[0].'">Delete</a></td>'; //The delete links should have 1 class name
Then make your ajax call
$('.lnk-delete').click(function(e){
var id = $(this).data('id');
ajax({
url: 'delete_back.php'
data: {id: id},
type: 'POST',
success: function(data){
$('#delete_msg').html(data);
}
});
});
Get the id of the item you want to delete in php
$id = $_POST['id'];
<?php
//select_back.php
echo "<td><a id='delete' href='#'>Delete</a></td>";
?>
<input type="hidden" id="hidden_id" name="id" value="<?php echo $row[0]; ?>">
<script>
$("#delete").click(function(event){
event.preventDefault();
var hidden_id =$("#hidden_id").val();
$.ajax({
type:'GET',
url:"delete_back.php",
data:"id="+hidden_id,
success:function(data){
if(data.trim() == 'success')
{
$("#delete_msg").html("<div style='color:green;'>deleted successfully</div>");
}else{
//error
}
}
});
});
</script>
<?php
// delete_back.php
$id=$_GET['id'];
include("config.php");
$data=mysqli_query($con,"delete from student where id='$id'");
if($data)
{
echo "success";
}
else
{
echo "Delete Error";
}
?>

How to pick multiple rows of values of the same id value from the database and display in ajax?

I have written code for button to send a value to php file using ajax as show below :
<script>
$(document).ready(function(){
$(".open-AddBookDialog").click(function(){
var packageid = $(this).attr("data-id");
var dataString = 'packageid='+ packageid;
$.ajax({
type: "POST",
url: "data1.php",
data: dataString,
cache: false,
success: function(result1){
var packagetype = package_type;
alert(packagetype);
}
});
});
});
</script>
This is the ajax code for the button which i have written. My button code is :
<a data-toggle="modal" id="custId" data-name="<?php echo $arr["package_name"]; ?>" data-id="<?php echo $arr["id"]; ?>" href="#myModal" class="open-AddBookDialog btn btn-submit" OnClick='change(this);'>Book / Enquiry / Pay</a>
When clicking this button in href, I want to send a id value to a php file using ajax.
data1.php
<?php
include('database.php');
$id=$_POST['packageid'];
$query1 = mysqli_query($con,"select * from ayurveda_packagetypes where package_id = '$id'");
$arr = mysqli_fetch_array($query1);
echo $arr['package_type'];
echo $arr['package_price'];
mysqli_close($con);
?>
using the id value, I want to pick multiple rows of package type and package price from the database having the same id value.After picking the multiple rows of these values i want to send it to the main php file and display all the values of all the rows picked from the database.
Can anyone suggest how to do this ?
<script>
$(document).ready(function()
{
$(".open-AddBookDialog").click(function()
{
var packageid = $(this).attr("data-id");
var dataString = 'packageid='+ packageid;
$.ajax(
{
type: "POST",
url: "data1.php",
data: dataString,
cache: false,
success: function(result)
{
resultJson=jQuery.parseJSON(result);
$.each(resultJson.packageDetails, function(i, item) {
var packagetype = item.package_type;
var package_price = item.package_price;
alert("packagetype :- "+packagetype+" ----- package_price :-"+package_price);
});
}
});
});
});
</script>
<?php
include('database.php');
$id=$_POST['packageid'];
$query1 = mysqli_query($con,"select * from ayurveda_packagetypes where package_id = '$id'");
//$arr = mysqli_fetch_array($query1);
while( $strPackageResult=mysqli_fetch_array($query1,MYSQLI_ASSOC) )
{ $ArrPackage[]=$strPackageResult; }
if( isset($strPackageResult) ){ unset($strPackageResult); }
mysqli_free_result($query1);
if( isset($query1) ){ unset($query1); }
$myResultPackageArray=array();
if( isset($ArrPackage) && is_array($ArrPackage) && count($ArrPackage)>0 ) {
$tempArray=array();
foreach( $ArrPackage as $tempPackage )
{
$tempArray['package_type']=$tempPackage['$tempPackage'];
$tempArray['package_price']=$tempPackage['package_price'];
$myResultPackageArray['packageDetails'][] =$tempArray;
}
}
mysqli_close($con);
echo json_encode($myResultPackageArray);
?>
There are some basic things you should know first then you can easily rectify your errors.
Debuging javascript
Prepared Statements
PHP Error Handling
This is not you have asked but as a programmer i will suggest you to go through it.
As going through your code
var packagetype = package_type;
package_type is undefined. If you are using chrome inspect element and check the console you will see the error.
Hope this will work.

Update Mysql records using Ajax/Json isn't working

What I'm trying to do is to edit mysql records using php. I've used Ajax/Json to edit a single record, but the problem is my codes isn't working. I tried to alert the value of input element after I clicked the save button and the alert output is verified. And also I don't get any message in console.
Here's what I got right now. Any help will appreciate.
Index.php
<div class="entry-form1">
<form action="" method="post">
<input type="text" name="id_edit" id="id_edit" class="inputs_edit">
<input type="text" name="approved_edit" id="approved_edit" class="inputs_edit">
<input type="submit" name="save_edit" id="save_edit" value="Save"/>
</form>
</div>
Search.php
$query1 = $mysqli->query(""); // not to include
while($r = $query1->fetch_assoc()){
<td><a href='#' name='".$r['id']."' id='".$r['pr_id']."' class='edits'>Edit</a></td>
}
<script>
$(document).ready(function(){
$(".edits").click(function(){
$(".entry-form1").fadeIn("fast");
//not to include some parts of codes
$.ajax({
type: "POST",
url: "auto-complete.php",
data :edit_post_value,
dataType:'json',
success:function(data){
var requested=data.requested;
var id=data.id;
//send to element ID
$('#id_edit').val(id);
$('#requested_edit').val(requested);
}
});
$("#save_edit").click(function () {
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data))
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});
</script>
Item_edit.php
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
if(isset($_POST['id_edit'])) {
$id_edit= $_POST['id_edit'];
$requested_edit= $_POST['requested_edit'];
$sql = $mysqli->query("UPDATE pr_list SET requested='$requested_edit' WHERE id='$id_edit'");
if($sql){
echo json_encode(array( "success" => "1"));
}else{
echo json_encode(array("success" => "0"));
}
}
?>
1) First, you're not capturing the click event, because $("# save_edit") is within a function that is not being called. So, you're not even sending the form to the server.
2) Second, the way a form works by default send the data and then reload the page, you must call the preventDefault() function from the event object captured to prevent it, before making the ajax call.
try this:
$(document).ready(function(){
$("#save_edit").click(function (e) {
e.preventDefault(); //prevent a page reload
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "/item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data));
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});

Call for another ajax from the result one ajax request got

I've header file in which I have search box where user can search for products, this works on ajax request & for getting the info I've livesearch.php file.
Now with the searched products, I want to add 'Add to Cart' button directly. So in fact for every search result there will be one button to add that product in cart. To achieve this, I need to add another ajax request for adding that product into cart.
But nothing's happening while I click on add button. Here's my code.
Header.php
<script type="text/javascript">
$(document).ready(function()
{
$(".searchproductbrand").keyup(function()
{
var kw = $(".searchproductbrand").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "livesearch.php",
data: "kw="+ kw,
success: function(option)
{
$("#livesearch").show();
$("#livesearch").html(option);
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
});
}
else
{
$("#livesearch").html("");
document.getElementById("livesearch").style.border="0px";
}
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function()
{
$(document).live('click', '.buynow', function()
{
var productid = $(this).attr('id');
var quantity = $('.quantity_'+productid).val();
var type= $('.type_'+productid).val();
$.ajax
({
type: "POST",
url: "db_addtocart.php",
data: {'quantity'=quantity, 'type'=type, 'productid'=productid},
success: function(option)
{
this.attr('value','Added');
}
});
return false;
});
});
</script>
<?php
<input type="text" id="text" class="searchproductbrand">
?>
livesearch.php
<?php
while(blah blah){
echo "<input type='text' id='quantity' class='quantity_".$row["productid"]."'>".
" <select name='type' class='type_".$row["productid"]."'>".
"<option value='Unit'>Unit</option>";
"</select>";
echo " <input type='button' class='button' id='".$row["productid"]."'
class='buynow' value='Buy Now'>";
}
?>
db_addtocart.php
This file gets the values of variables & insert into table, nothing sort of important.
What wrong am I doing? Any help will be appreciated.
Try updating your js to the code below. I used .delegate() instead of .live() as according to the manual it is better to use with jQuery 1.4.3+.
$(document).ready(function() {
$(".searchproductbrand").keyup(function(){
var kw = $(".searchproductbrand").val();
if(kw != ''){
$.ajax({
type: "POST",
url: "livesearch.php",
data: {kw:kw},
success: function(option){
$("#livesearch").show();
$("#livesearch").html(option);
$("#livesearch").css("border","1px solid #A5ACB2"); // used $('#...') instead of document.getElementById() AND .css() instead of style.border
}
});
}
else {
$("#livesearch").html("").css("border","0px"); // used $('#...') instead of document.getElementById() AND .css() instead of style.border
}
return false;
});
$(document).delegate('.buynow','click', function(){
var productid = $(this).attr('id');
var quantity = $('#quantity_'+productid).val(); // changed from .quantity_ to #quantity - requires change in php code
var type= $('#type_'+productid).val(); // changed from .type_ to #type - requires change in php code
$.ajax({
type: "POST",
url: "db_addtocart.php",
context: this, // added as 'this' below was out of scope. see the docs for more info
data: {quantity:quantity,
type:type,
productid:productid},
success: function(option){
this.value = 'Added'; // changed from this.attr('value','Added');
}
});
return false;
});
});
This will also require you to update the html created in livesearch.php to the following code. Mainly changing from class=... to id=...
<?php
while(blah blah){
echo "<input type='text' id='quantity_".$row["productid"]."' />";
echo " <select name='type' id='type_".$row["productid"]."'>".
"<option value='Unit'>Unit</option>".
"</select>";
echo " <input type='button' class='button buynow' id='".$row["productid"]."' value='Buy Now'>";
}
?>
Here is a working JSFiddle example - http://jsfiddle.net/X8n3d/
What's going on is that your $(".buynow").click is bound to the element which are in the dom on load of your page. Any button with .buynow added after that has no event.
You need to use jQuery's on() method so the click event works for all elements.
Juste replace $('.buynow').click(function(e){..}) with $(document).on('click', '.buynow', function(e){..}) and it should work.

Get value from jQuery AJAX to PHP

Working on a project where I want to be able to delete a dynamic record using jQuery and PHP. I already have the option for users to add a record dynamically it is just getting the delete option to work. While I am trying to develop this function I have set the Delete to INSERT. Where I am having trouble is getting the value from the hidden field to delete-class.php (the bottom script). Below I have posted the code:
<form id="frmDelete" method="post" action="delete-class.php">
<input id="btnSubmit" type="submit"/>
<ul id="class">
<?php
//this is being loaded from a different page and is here just to reference the fields
while ($row = mysql_fetch_array($result)) {
echo '<li id="liClass" class="ui-widget"><img src="trash-can-icon.png" id='.$row["id_distance_class"].' class="delete"/>' . $row["class_section"] . '<input type="hidden" name="hdid" id="hdid" value="'.$row["id_distance_class"].'"/></li>';
?>
</ul>
</form>
<script>
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = id ;
// console.log(id);
$.ajax({
type: "POST",
url: "delete-class.php",
data: $(this).serialize(),
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
</script>
//this is the delete-class.php
$results = mysql_query("INSERT INTO distance_class (class_section) VALUES ( '".$_POST['hdid']."' ) ");
The problem is you're not passing this information in your AJAX request. You're passing
data: $(this).serialize()
...presumably thinking this points to the form. It doesn't; it points to the deletion button clicked, since this code is running in the button's event handler callback.
Change the above to target the form.

Categories