There's something wrong with my codes and I'm unable to run it successfully. When I debug my Ajax code using Google Developer tools, Ajax data parameter has the value of the primary key (uid) but it seems it doesn't send POST request to delete.php. I've no idea what the problem is.
Thanks for your helps and suggestions in advance!
index.php: Press Delete Button to Fire Ajax Code
<tbody>
<!--Populate HTML Table-->
<?php if(!empty($records)) {
foreach ($records as $record) {
?>
<tr>
<td data-target="rowNum"></td>
<td data-target="userId" style="display: none;">
<?php echo $record['uid']; ?>
</td>
<td data-target="firstname"><?php echo $record['first_name']; ?></td>
<td data-target="lastname"><?php echo $record['last_name']; ?></td>
<td data-target="emailaddress"><?php echo $record['email_address']; ?></td>
<td>
<button class="btnEdit">Edit</button>
<!--Press Delete Button to Fire Ajax Code-->
<button class="btnDelete">Delete</button>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
Ajax Code: Send userId (Table Primary Key) as Data to Delete.php
$(document).ready(function(){
$(".btnDelete").click(function(){
var userId = $(this).closest("tr").children("td[data-target=userId]").text();
$.ajax({
url: "delete.php",
type: "POST",
data: userId
});
});
});
delete.php:
<?php
include 'database.php';
$conn->query("DELETE FROM Users WHERE uid = '$_POST['userId']'");
?>
You pass your data like this:
$.ajax({
url: "delete.php",
type: "POST",
data: userId
});
userId value is probably just a scalar without key that you're trying to use in delete.php. So change this code to:
$.ajax({
url: "delete.php",
type: "POST",
data: { userId: userId }
});
and it should work.
this might help, you are send data as text.
$(document).ready(function(){
$(".btnDelete").click(function(){
var userId = $(this).closest("tr").children("td[data-target=userId]").text();
$.ajax({
url: "delete.php",
type: "POST",
contentType: 'text/plain'
data: {userId:userId}
});
});
});
You can probably get it to run the way you are trying to but here's a way that makes a bit more sense to me:
<tbody>
<!--Populate HTML Table-->
<?php if(!empty($records)) {
foreach ($records as $record) {
?>
<tr>
<td data-target="rowNum"></td>
<td data-target="firstname"><?php echo $record['first_name']; ?></td>
<td data-target="lastname"><?php echo $record['last_name']; ?></td>
<td data-target="emailaddress"><?php echo $record['email_address']; ?></td>
<td>
<button class="btnEdit">Edit</button>
<!--Press Delete Button to Fire Ajax Code-->
<form class="deleteForm" method="POST">
<input type="hidden" name="userId" value="<?= $record['uid'] ?>" />
<button type="submit" class="btnDelete">Delete</button>
</form>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
Then in JavaScript
$(document).ready(function(){
$(".deleteForm").on('submit', function(){
var data = $(this).serialize(); // Let jQuery prepare the data
$.ajax({
url: "delete.php",
type: "POST",
data: data
});
return false; // Cancel default
});
});
Lastly:
<?php
include 'database.php';
$userId = filter_input(INPUT_POST, 'userId', FILTER_VALIDATE_INT); //Assuming an ID is an int, in general be cautions of SQL injection.
if ($userId) {
$conn->query("DELETE FROM Users WHERE uid = '$_POST['userId']'");
} else {
http_response_code(400); // Missing the input
die();
}
?>
Related
I have two same name multiple input fields. I want to send all fields value from another page using jquery ajax post method but i am not getting all rows input fields value. Please review my code.
Javascript code
<script type="text/javascript">
function getValue()
{
$.post("paidamt.php",
{
paidamt : $('#paidamt').val(),
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Html Code
<div>
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" id="paidamt"></td>
<td><input type="checkbox" name="uid[]" id="uid"
value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<input type="button" name="submit" id="submit"
onclick="getValue(1)" value="Save Amt.">
</form>
</div>
<div id="divShow">
</div>
Try this one
var paidamt = $("input[name=paidamt]").map(function(){
return $(this).val();
}).get().join(",");
var uid = $("input[name=uid]").map(function(){
return $(this).val();
}).get().join(",");
$.ajax(
{
type: "POST",
url: 'paidamt.php',
data:
{
paidamt:paidamt,
uid:uid
}
});
Firstly you have given the input elements the same id which is repeated in the loop. This will end up in your HTML being invalid, you should change the id to class:
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) { ?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" class="paidamt"></td>
<td><input type="checkbox" name="uid[]" class="uid" value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<button type="submit" name="submit" id="submit">Save Amt.</button>
</form>
To actually send the input values in the AJAX request you can simply serialize() the containing form when the form is submit:
$(function() {
$('form').submit(function(e) {
$.ajax({
url: "paidamt.php",
type: 'POST',
data: $(this).serialize(),
success: function(data) {
$("#divShow").html(data);
});
});
});
});
I suggest to add class instead of id, since identically class can be repeated but id should not.
<script type="text/javascript">
function getValue()
{
var paidamtval = [];
$('#paidamt').each(function(){
paidamtval.push($(this).val());
});
$.post("paidamt.php",
{
paidamt : paidamtval,
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Since you will have many of these, id - needs to be unique, which in your case isn't, so remove "id="paidamt"
<td><input type="text" name="paidamt[]" id="paidamt"></td>
That's your first mistake. And secondly don't use $.post, to submit this form. Either remove AJAX submit, or bind form using something like jQuery Form plugin.
You try this code
$('document').ready(function(){
$('#submit').click(function(){
jQuery.ajax({
type: "POST",
url: "paidamt.php",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(html){
try{
$("#divShow").html(data);
}catch (e){
alert(JSON.stringify(e));
}
},
error : function(e){alert("error "+JSON.stringify(e)); }
});
});
});
in you paidamt.php file
$paidamt=$_POST['paidamt'];// its can array values
print_r($paidamt);// result display
I'm trying to display a list of players with a edit button next to each one. When edit is pressed, then the user can edit that player. I'm trying to do this using ajax. The problem: The table will display for a split second then it's a blank screen.
<?php foreach($players as $player): ?>
<tr>
<td><?= $player['first_name']; ?></td>
<td><?= $player['last_name']; ?></td>
<td><?= $player['email']; ?></td>
<td align="center" >
<form action="" method="post" id="edit_player">
<input type="hidden" name="user_id" value="<?= player['user_id']; ?>">
<input type="submit" value='Edit' name='submit'>
</form>
</td>
</tr>
<?php endforeach;?>
Here is my jquery/ajax code. I made some changes from earlier. I think it's better, but it's still not working.
$(document).ready(function() {
var contents = $('#teamMain');
$('.edit_player').each(function(index, value) {
var formData = $(this).attr('user_id');
$.ajax({
url: 'views/team_nav.php',
type: 'POST',
cache: false,
data: formData,
success: function(data){
contents.html(data);
}
});
});
});
I implemented a project in Yii. I want to delete data from table using ajax function.
In my controller I wrote this:
public function actionDelete1(){
if (isset($_POST['x1']) && isset($_POST['r_id'])) {
$hid=$_POST['x1'];
$rid=$_POST['r_id'];
echo $_POST['x1'].'recipe_id'.$_POST['r_id'];
$query="delete from ingredients where ingredienttype_id='$hid'";
$query1=Yii::app()->db->CreateCommand($query)->execute();
$this->redirect(array('recipe/update','id'=>$rid));
}
}
In my view part:
<script>
function removeRow1(x,y){
alert("Are sure want to delete");
$.ajax({
url: '<?php echo Yii::app()->createAbsoluteUrl("ingredients/delete1"); ?>',
type: 'POST',
data: 'x1='+x+'&r_id='+y,
success: function(res)
{
//alert(res);
////$("#truth").html(res);
},
error:function(){
alert("Failed request data from ajax page");
}
});
}
</script>
I display these three table data with one row:
<td id="data">
<?php
echo $i++;
?>
</td>
<td id="data">
<?php
$type=Ingredienttype::model()->find("id=$type_id");
echo $type['ingredient_type'];
?>
</td>
<td id="data">
<?php
$type1=Ingredient::model()->find("ingredient_id=$ingredient_id");
//echo $ingredient_id;
echo $type1['ingredientname'];
?>
</td>
<td id="data">
<?php
echo $quantity;
?>
</td>
<td id="data">
<?php
$mes_type=Measuringtype::model()->find("id=$measuringtype");
echo $mes_type['measuringname'];
?>
</td>
<input type="button" id="<?php echo $type_id; ?>" name="doesntMatter" class="REMOVETHIS btn btn-inverse btn-xs"
value="Del" onclick="removeRow1(this.id,<?php echo $model->recipe_id ?>)"/></td>
It's not working. Please suggest me how to delete ID using ajax.
First you have
$query="delete from ingredients where ingredienttype_id='$hid'";
where $hid is not defined yet!
Would you use either $hid or $rid ?
Secondly, sending params with ajax, data should be an object, I don't know if it works with a string. so to be sure, try using an object as follows
$.ajax({
url: '<?php echo Yii::app()->createAbsoluteUrl("ingredients/delete1"); ?>',
type: 'POST',
data: {'x1':x,'r_id':y},
success: function(res)
{
//----
i am making a website in which i am to embbed the functionality of delete using multiple checkbox. here is my code. my problem is
1. Ajax call is not working.
2. how can i make search from database for array .
<?php
if(isset($_POST['Delete']))
{
$array=$_POST['check_box'];
}
?>
<form method="post" id="form">
<table width="200" border="1">
<tr>
<td>select</td>
<td>NAme</td>
<td>Action</td>
</tr>
<?php
while($selectnumberarr=mysql_fetch_array($selectnumber))
{
?>
<tr>
<td><input type="checkbox" name="check_box[]" class="check_box" id="<?php $selectnumberarr[0]; ?>" /> </td>
<td><?php echo $selectnumberarr[1]; ?></td>
</tr>
<?php
}?>
<input type="submit" name="Delete" id="delete">
</table>
</form>
and below is my ajax and javascript code.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#delete').click(function() {
$.ajax({
type: "POST",
url: "checkbox.php",
data: $('#form').serialize(),
cache: false,
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
any help would be appriciated
your code is almost correct. You need to remove `onChange="show()" for input checkbox, because if you have jquery then you don't need to put events on HTML elements.
Use jquery 'on' method for compatibility for latest php library.
Replace your jquery code with following jquery code :-
<script>
$(document).ready(function(){
$('#delete').on('click',function()
{
var cat_id = $('.check_box:checked').map(function() {
return this.id;
}).get().join(',');
console.log(cat_id);
$.ajax({
type: "POST",
url: "checkbox.php",
data: { "kw ":cat_id },
datatype:'json',
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
Use ".check_box" instead of "element" in jquery to prevent checks for all checkboxes, instead of desired ones.
Hope it helps.
Why you don't use an array for sending the checkboxes like:
HTML part:
<?php
if (isset($_POST['check_box'])) {
var_dump($_POST['check_box']);
echo "ajax call is working";
}
?>
<form id="form">
<table width="200" border="1">
<tr>
<td>select</td>
<td>NAme</td>
<td>Action</td>
</tr>
<?php
while ($selectnumberarr = mysql_fetch_array($selectnumber)) {
?>
<tr>
<td><input type="checkbox" name="check_box[]" class="check_box" value="<?php echo $selectnumberarr[0]; ?>" /> </td>
<td><?php echo $selectnumberarr[1]; ?></td>
</tr>
<?php
}
?>
</table>
<input type="button"name="delete" id="delete" value="Delete" />
</form>
JQuery part:
<script type="text/javascript">
$(document).ready(function(){
$('#delete').click(function() {
$.ajax({
type: "POST",
url: "checkbox.php",
data: $('#form').serialize(),
cache: false,
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
So you can easily get an array of the selected checkboxes in php with:
$idsArray = $_POST["check_box"];
this looks now like:
array(
"1", "2","etc.."
);
so this array contains all the ids of the selected checkboxes for delete.
I would like to know why my following code piece displays nothing in the browser (http://localhost/display.php). I would like to generate a template for my table to display all employees in my database (id, firstname, lastname) and use HTTP verb DELETE via jquery ajax method to delete a user if I click the delete button on the display table.
Here is my display.php
<table id="employees" border="1">
</table>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$document.ready(function()
{
var $employees = $("#employees");
$.ajax({
url: "delete.php",
contentType: "json",
success: function(data){
$.each(data, function(index, item){
var $row = $("#templates").find(".row-template").clone();
$row.find(".firstName").html(item.FirstName);
$row.find(".lastName").html(item.LastName);
$row.find(".delete").click(function() {
$.ajax({
url: "delaction.php" + item.Id,
type: "DELETE",
success: function()
{
$row.remove();
}
});
});
$employees.append($row);
});
}
});
});
</script>
<div id="templates" style="display: none">
<table>
<tr class="row-template">
<td class="firstName" style="width: 100px;"></td>
<td class="lastName" style="width: 100px;"></td>
<td>
<input type="button" value="X" class="delete" />
</td>
</tr>
</table>
</div>
and my delete.php looks like this
<?php
define('DB_HOST','localhost');
define('DB_ROOT','root');
define('DB_PASS','');
define('DB_NAME','employees');
$conn=mysqli_connect(DB_HOST,DB_ROOT,DB_PASS) or die("Unable to connect to your selected db.Error ".mysqli_error());
if(null!=$conn)
{
mysqli_select_db($conn,DB_NAME);
$query=("SELECT * FROM empl");
$result=mysqli_query($query);
foreach($result as $res)
{
}
mysqli_close($conn);
}
?>
Thank you a lot.
What's in 'delaction.php'?
Anyway, to pass itemId to delaction.php with the item to delete, change:
url: "delaction.php" + item.Id,
to:
url: "delaction.php?itemId=" + item.Id,