Ajax confirmation is asking only for one data - php

I have implemented an ajax beforeSend function where there is a confirm(), the problem is that in the code if I want to delete the first value in while it asks for confirm but if I click the second or third or fourth, it just goes to the URL in the method and executes the command
this is the the page
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Button</th>
</tr>
</thead>
<tbody>
<?php
$stmt = $DB_con->prepare("SELECT * FROM people");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{?>
<tr><td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<form method="post" id="del" action="delete.php">
<input type='hidden' id='pid' name='pid' value='<?php echo $row['id']; ?>'>
<button id="send" type="submit">Delete</button>
</form>
</th>
</tr>
<?php
}
?>
this is the ajax function
$(document).ready(function (e) {
$("#del").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "delete.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend:function(){
return confirm("Are you sure you want to delete this?");
},
success: function(data)
{
alert("Delete Successful");
window.location.reload();
},
error: function(e)
{
}
});
}));
});
whereas it should ask no matter which record I want to delete, it should ask for confirmation.

use classname class="del" instead of id id="del".Each time submit its only execute first form
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Button</th>
</tr>
</thead>
<tbody>
<?php
$stmt = $DB_con->prepare("SELECT * FROM people");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{?>
<tr><td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<form method="post" class="del" action="delete.php">
<input type='hidden' class='pid' name='pid' value='<?php echo $row['id']; ?>'>
<button id="send" type="submit">Delete</button>
</form>
</th>
</tr>
<?php
}
?>

Here you create invalid HTML:
while(...)
{
...
'>
Delete
...
}
In every loop-run you create 3 objects with identical id in each run. An ID must not defined multiple times.
Solutions:
Don't use id=and use optional class=.
Append an unique number to id, e.g. id="del-<?php echo $row['id']; ?>"

Related

Instant Checkbox update on sql rows with ajax and jquery

Example of what I want:
Hi i want on each row to update instant the checkbox with value 1 when checked and 0 when not checked.
I've make some steps and already taken in a URL via post the values, but I see that updates only on the first row of my table. I think it must have some foreach or loop on ajax to take value to other rows?
This value will export as a URL querystring (ischeck) to an extrnal URL to take import on my function to make the sql query to update the value.
Here is the javascript that for sure want changes about loop that I haven't put on charges.php.
<script>
$(function($) {
var arr = [];
$('input.checkbox').on('change', function() {
var id = "<?php echo $charge['id'] ?>";
var check_active = $(this).is(':checked') ? 1 : 0;
var check_id = $('[id^="checked-]');
arr.push(check_active);
var url = "ajax_ischeck.php?id=" + id + "&ischeked=" + check_active;
console.log("url", url);
if (this.checked) {
$.ajax({
url: url,
type: "GET",
dataType: 'html',
success: function(response) {
},
});
}
});
});
</script>
Here is the table with the input checkbox sry its little big the checkbox is down to last lines on Charges.php:
<tbody>
<?php foreach ($showcharge as $charge) { ?>
<tr>
<td><?php echo htmlspecialchars($charge['created_at']); ?></td>
<td><?php echo htmlspecialchars($charge['tasks']); ?> </td>
<th width="5%"><?php if (empty($charge['taskcharges'])) {
echo "Free";
} else {
echo htmlspecialchars($charge['taskcharges'] . "\xE2\x82\xAc");
} ?></th>
<th width="5%"><?php
if (empty($charge['payment'])) {
echo htmlspecialchars($charge['payment']);
} else {
echo htmlspecialchars($charge['payment'] . "\xE2\x82\xAc");
}
?>
</th>
<th width="5%" id="balance"><?= htmlspecialchars($charge['balance'] . "\xE2\x82\xAc") ?></th>
<th width="10%"><?php if (($charge['payment_date'] == 0000 - 00 - 00)) {
echo "";
} else {
echo htmlspecialchars($charge['payment_date']);
} ?></th>
<th width="10%"><?php echo htmlspecialchars($charge['admin']); ?></th>
<th width="15%"><?php echo htmlspecialchars($charge['comments']); ?></th>
<td class="mytd">
<form action="" method="POST">
<a href="editcharge.php?id=<?php echo $charge['id'];
echo '&custid=' . $customer['id'] ?>" class="btn btn-info " role=" button " aria-disabled=" true">Edit</a>
</form>
<form id="delete-<?php echo $charge['id'] ?>" onSubmit="return confirm('Are you sure you want to delete?')" method="post">
<input type="hidden" name="id_to_delete" value="<?php echo $charge['id'] ?>" />
<input type="submit" class="btn btn-danger" name=" delete" value="delete" />
</form>
<script>
$("#delete").submit(function() {
return confirm("Are you sure you want to delete?");
});
</script>
</td>
<th width="7%"> <input class="checkbox" type="checkbox" checked value="1" id="checked-1" name="checbox"> <label> Success </label> </input> </th>
</tr>
<?php } ?>
</tbody>
The ajax_ischeck.php that gets data from charges.php post :
<?php include('dataprocess.php'); ?>
<?php include('config/pdo_connect.php'); ?>
<?php
$id = $_GET['id'];
$ischeck = $_GET['ischeck'];
if(isset($_GET["ischeck"])){
Data::ischecked($id, $ischeck);
}
and the sql query:
public static function ischecked ($id, $ischeck)
{
$sql = "UPDATE charges SET
ischecked='$ischeck'
WHERE id=$id";
$statement = conn()->prepare($sql);
$statement->execute();
/* echo $sql;
die(); */
if (!$statement) {
echo "\nPDO::errorInfo():\n";
}
}

How to get data from server when I enter something in search box and I press add more button? Adds other row of product search box in jQuery AJAX

Hello every one I need help for getting auto search product values for dynamic adding of a product search box, when I type a product id it will show from product table. Please help me to get a dynamic auto search box.
Here is the code for the main html page:
<table id="row2">
<tr id="row1">
<td>product id</td><td><input type="text" id="pid" class="pid" name="p_id">
<div id="suggesstion-box"></div></td>
<td>product name</td> <td><input type="text" id="pname" name="p_name"></td>
<td>product type</td> <td> <input type="text" id="ptype" name="p_type">
</td>
<td>product colour</td> <td> <input type="text" id="pcolor" name="p_colour"></td>
</tr>
</table>
<button name="b1" id="b1" onClick="addrow()">Add More</button>
This the code for jQuery:
$(document).ready(function(){
$("#pid").keyup(function(){
$.ajax({
type: "POST",
url: "readCountry.php",
data:'keyword='+$(this).val(),
beforeSend: function(){
$("#pid").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px");
},
success: function(data1,data2){
$("#suggesstion-box").show();
$("#suggesstion-box").html(data1);
$("#fname").html(data2);
$("#pid").css("background","#FFF");
}
});
});
});
function addrow()
{
//alert('hello');
$('#row2').append("<tr><td>product id</td><td><input type='text' class='pid' id='pid' name='p_id'><div id='suggesstion-box'></div></td><td>product name</td> <td><input type='text' id='pname' name='p_name'></td><td>product type</td> <td> <input type='text' id='ptype' name='p_type'></td><td>product colour</td><td> <input type='text' id='pcolor' name='p_colour'></td></tr>");
}
function selectCountry(val) {
$("#pid").val(val);
$("#suggesstion-box").hide();
}
function name(val){
$("#pname").val(val);
}
function pt(val){
$("#ptype").val(val);
}
function colour(val){
$("#pcolor").val(val);
}
readcountery.php page code is:
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["keyword"])) {
$query ="SELECT * FROM raw_product WHERE p_id like '%" . $_POST["keyword"] . "%' ORDER BY p_id LIMIT 0,6";
$result = $db_handle->runQuery($query);
if(!empty($result)) {
?>
<ul id="country-list">
<?php
foreach($result as $country) {
?>
<li onClick="selectCountry('<?php echo $country["p_id"]; ?>'); colour('<?php echo $country["p_color"]; ?>'); pt('<?php echo $country["p_color"]; ?>'); name('<?php echo $country["p_name"]; ?>');"><?php echo $country["p_id"]; echo "-".$country["p_name"]; ?></li>
<?php } ?>
</ul>
<?php } } ?>

How to get values from foreach loop of php in jquery

I'm Working on a plugin in Wordpress in which i'm storing values in new table which is created on plugin activation its working perfectly.
Now I fetched values from table like following
<tbody>
<?php
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM wp_ajc_images");
foreach ($result as $row) {
?>
<tr id="list_item">
<td width="12%">
<img src="<?php echo $row->ajc_img_path ?>" width="100">
</td>
<td width="22%">
<input type="text" class="img_link" value="<?php $row->ajc_img_link ?>" size="30">
<input type="hidden" class="ajc_field_id" value="<?php echo $row->ajc_img_id ?>">
</td>
<td width="26%">
<textarea rows="3" class="img_description"><?php $row->ajc_img_description ?></textarea>
</td>
<td width="22%">
<input type="text" class="img_title" value="<?php $row->ajc_img_title ?>" size="30">
</td>
<td width="20%">
<input type="submit" id="update" value="Update">
<button class="delete">Delete</button>
</td>
</tr>
<?php
}
?>
</tbody>
after fetching the data I display the values in form of listing.
Now I want to update values of input fields and textarea through ajax for which I wrote following code
add_action('wp_ajax_ajc_update_values', 'ajc_update_value');
add_action('wp_ajax_nopriv_ajc_update_values', 'ajc_update_value');
add_action("admin_head", "ajc_input_ajax");
function ajc_input_ajax()
{
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#update").click(function () {
var id = jQuery('.ajc_field_id').val();
var update_link = jQuery('.img_link').val();
var update_desc = jQuery('.img_description').val();
var update_title = jQuery('.img_title').val();
alert(id);
var data = {
action: 'ajc_update_values',
ajc_id: id,
ajc_update_link: update_link,
ajc_update_desc: update_desc,
ajc_update_title: update_title
};
alert(data.toSource());
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (result) {
// alert(result);
});
});
});
</script>
<?php
}
//Updating values in database
function ajc_update_value()
{
$id = $_POST['ajc_id'];
$link = $_POST['ajc_update_link'];
$desc = $_POST['ajc_update_desc'];
$title = $_POST['ajc_update_title'];
global $wpdb;
$wpdb->update(
'wp_ajc_images',
array(
'ajc_img_title' => $title,
'ajc_img_description' => $desc,
'ajc_img_link' => $link
),
array('ajc_img_id' => $id)
)
die();
return true;
}
When I click on first item's update button it alerts me right id eg. (12) and update it, but when I click on rest of the item's update button it alerts me first item's id (12) and data is not updated.
Hope you'll understand my question.
Try this code. add id to every fields like id="img_link_<?php echo $row->ajc_img_id; ?>"
HTML code
<tbody>
<?php
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM wp_ajc_images");
foreach ($result as $row) {
?>
<tr id="list_item">
<td width="12%">
<img src="<?php echo $row->ajc_img_path ?>" width="100">
</td>
<td width="22%">
<input type="text" id="img_link_<?php echo $row->ajc_img_id; ?>" class="img_link" value="<?php $row->ajc_img_link ?>" size="30">
<input type="hidden" class="ajc_field_id" value="<?php echo $row->ajc_img_id; ?>">
</td>
<td width="26%">
<textarea rows="3" id="img_description_<?php echo $row->ajc_img_id; ?>" class="img_description"><?php $row->ajc_img_description ?></textarea>
</td>
<td width="22%">
<input type="text" id="img_title_<?php echo $row->ajc_img_id; ?>" class="img_title" value="<?php $row->ajc_img_title ?>" size="30">
</td>
<td width="20%">
<input type="submit" data-id="<?php echo $row->ajc_img_id; ?>" id="update" value="Update">
<button class="delete">Delete</button>
</td>
</tr>
<?php
}
?>
</tbody>
Script code
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#update").click(function () {
var id =jQuery(this).attr('data-id');
var update_link = jQuery('#img_link'+id).val();
var update_desc = jQuery('#img_description'+id).val();
var update_title = jQuery('#img_title'+id).val();
alert(id);
var data = {
action: 'ajc_update_values',
ajc_id: id,
ajc_update_link: update_link,
ajc_update_desc: update_desc,
ajc_update_title: update_title
};
alert(data.toSource());
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (result) {
// alert(result);
});
});
});
</script>
You're displaying values based on a class name and there could be many elements with same class name. What you need to do is target specific <tr> and get values from that <tr> only.
So your jQuery code should look like this:
jQuery("#update").click(function () {
var id = $(this).parents('tr').find('.ajc_field_id').val();
var update_link = $(this).parents('tr').find('.img_link').val();
var update_desc = $(this).parents('tr').find('.img_description').val();
var update_title = $(this).parents('tr').find('.img_title').val();
alert(id);
var data = {
action: 'ajc_update_values',
ajc_id: id,
ajc_update_link: update_link,
ajc_update_desc: update_desc,
ajc_update_title: update_title
};
alert(data.toSource());
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (result) {
// alert(result);
});
});
You just have to add $(this).parents('tr').find before selecting values from every element.

Form action not allowing the delete of a record

I had to add a form action to go to a different page to edit a specific record, but with doing that, it won't allow me to delete a record because it is taking me away from it before it will do the query. I am unsure of how to make this work and still get to the new page when I hit the "Edit" button.
<table id="tableid">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Product</th>
<th>Save</th>
<th>Delete</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$stmt = $dbc->query("SELECT `id`,`first`,`last`,`product` FROM users");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()) {
?>
<form method="POST" action="edit-product">
<tr>
<td><?php echo $row['id'];?>"</td>
<td><?php echo $row['first'];?></td>
<td><?php echo $row['last'];?></td>
<td><?php echo $row['product'];?></td>
<input name="id" type="hidden" value="<?php echo $row['id'];?>" readonly>
<input name="first" type="hidden" value="<?php echo $row['first'];?>">
<input name="last" type="hidden" value="<?php echo $row['last'];?>">
<input name="product" type="hidden" value="<?php echo $row['product'];?>">
<td><input name="save" type="submit" value="Save"></td>
<td><div class="delete-class" name="delete" id="<?php echo $row['id']; ?>">Delete</div></td>
<td><input name="edit" type="submit" value="Edit"></td>
</tr>
</form>
<?php } ?>
</tbody>
</table>
PHP DELETE query
if(isset($_POST['delete'])) {
$id = $_POST['id'];
$stmt = $dbc->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
}
How can I change the markup to still get both the edit (going to another page with the action) and the delete to work on this page?
UPDATE AJAX code:
$(function() {
$(".delete_class").click(function(){
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'delete-product.php',
data:'delete_id='+del_id,
success:function(data) {
if(data) { // DO SOMETHING
} else { // DO SOMETHING }
}
)); //here
});
});
This is not very ideal but one way to do it. You change the HTML markup to create two forms, one for edit case and another one for Delete. The delete case sends the request to the current page like this:
while($row = $stmt->fetch()) {
?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['first'];?></td>
<td><?php echo $row['last'];?></td>
<td><?php echo $row['product'];?></td>
<td>
<form method="post" action="edit-product">
<input name="id" type="hidden" value="<?php echo $row['id'];?>">
<input name="first" type="hidden" value="<?php echo $row['first'];?>">
<input name="last" type="hidden" value="<?php echo $row['last'];?>">
<input name="product" type="hidden" value="<?php echo $row['product'];?>">
<input name="save" type="submit" value="Edit">
</form>
</td>
<td>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input name="id" type="hidden" value="<?php echo $row['id'];?>">
<input name="delete" type="submit" value="Delete">
</form>
</td>
</tr>
<?php }
?>
</tbody>
</table>
<?php
// the delete code goes here
if(isset($_POST['delete'])) {
$id = $_POST['id'];
$stmt = $dbc->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
}
?>
I left out the save case but it will be similar to edit case.
Rather than having a form you could just have links instead of form submit buttons. That way each link could take you to a specific page that performs a specific task. By passing query string variables and using $_GET rather than $_POST, you can retain the product ID information.
Example:
<td>Save</td>
<td>Delete</td>
<td>Edit</td>
These individual pages could then perform your tasks in the database. Both save and delete could use Header re-directs to get back to your original page with your product list.
delete_product.php Example:
// delete product from database
$id = $_GET['id']; // Note that it's a $_GET
$stmt = $dbc->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
// re-direct to original list page
header("Location: product_list.php"); // or whatever you have your list page named.
The edit_product.php page would then have your typical form for making changes to a specific product. You will need to lookup the product again in the database using $_GET['id'] value to match it with.
As it was suggested in the comments, using AJAX would make the whole process appear to be seamless, rather than jumping around between pages and being re-directed.

update the database without page refresh

Whenever the hyperlink with the yes id is clicked i dont want the page to refresh and then show the status, i want the status to change instant without page refreshing. I know Ajax deals with this, but can anyone provide me with a working example with my code please? As it melting my head :/
<h3 class="page-header"> Enquiries </h3>
<form id="enquiry" method="post" action="enquiry_csv.php">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th> First Name</th>
<th> Last Name</th>
<th>Email</th>
<th>Message</th>
<th>Date</th>
<th>Responded to Enquiry?</th>
<th>Status</th>
<th></th>
<th><input class='btn-success' name='export' id='btnExport' type='submit' value='Export to CSV'/></th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM enquiries";
$select_enquiries = mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($select_enquiries)) {
$Enquiry_ID = $row['Enquiry_ID'];
$FirstName = $row['First_Name'];
$LastName =$row['Last_Name'];
$Email = $row['Email'];
$Message = $row['Message'];
$Date =$row['Date'];
$Responded =$row['Responded'];
echo "<tr>";
echo "<td>$FirstName </td>";
echo "<td>$LastName </td>";
echo "<td>$Email </td>";
echo "<td>$Message </td>";
echo "<td>$Date </td>";
echo "<td> <a id='yes' class='success' style='' href='enquiries.php?Yes=$Enquiry_ID'>Yes</a> | <a class='success' href='enquiries.php?No=$Enquiry_ID'>No</a> </td>";
echo "<td> $Responded</td>";
echo "<td> <a class='btn btn-danger' href ='enquiries.php?delete=$Enquiry_ID'>Delete</a> </td>";
echo "</tr>";
}
?>
<?php
if(isset($_GET['Yes'])){
$enquiry_id = $_GET['Yes'];
$query = "UPDATE enquiries SET Responded = 'Yes' WHERE Enquiry_ID = {$Enquiry_ID}";
$query = mysqli_query($connection, $query);
}
if(isset($_GET['No'])){
$enquiry_id = $_GET['No'];
$query = "UPDATE enquiries SET Responded = 'No' WHERE Enquiry_ID = {$Enquiry_ID}";
$query = mysqli_query($connection, $query);
}
if(isset($_GET['delete'])){
$review_id = $_GET['delete'];
$query = "DELETE FROM enquiries WHERE Enquiry_ID = {$Enquiry_ID} ";
$delete_query = mysqli_query($connection, $query);
}
?>
<tr>
<td></td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</form>
You can do it with jquery ajax api it performs an asynchronous HTTP (Ajax) request
http://api.jquery.com/jquery.ajax/
Refer the above link which #Sanya Zahid posted and try to do some thing like this:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var age = $("#age").val();
var dataString = 'name='+ name +'&age='+ age;
if(name=='' || age =='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
<form method="post" name="form">
<input id="name" name="name" type="text" /><br>
<input id="age" name="age" type="text"/>
<div>
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Data</span>
<span class="success" style="display:none"> Data Saved!!</span>
</div>
</form>
Here submit.php contains database related stuff(insert/update/delete). I just added name and age fileds here in code. Add fields as per your form.
submit.php :
<?php
$conn = mysqli_connect("localhost","root","","test");
/* Insert form data with out page refresh */
if($_POST)
{
$name=$_POST['name'];
$age = $_POST['age'];
mysqli_query($conn,"Query will come here");
}else{
echo "Please try again!!";
}
/* Insert form data with out page refresh */
?>

Categories