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)
{
//----
Related
Hey Everyone here is my question .
The code below gets data from my database and displays it both in an input field and a button. I want it to be in such a way that if i click the button it should get the value(which is imported from the db).But the problem i am facing is that all the inputs and buttons have the same ids so it only captures the value of the first button(or so i think). How can i make it in such a way that for every button i click it should have its own separate value.
<?php
$dbcon=mysqli_connect("localhost","root","");
mysqli_select_db($dbcon,"codex");
require('config/server.php');
?>
<table class="table table-striped">
<th>ID</th>
<?php
$view_users_query="select * from users";//select query for viewing
users.
$run=mysqli_query($dbcon,$view_users_query);//here run the sql
query.
while($row=mysqli_fetch_array($run))//while look to fetch the result
and store in a array $row.
{
?>
<!--here showing results in the table -->
<form id="loginForm" method="" action="" novalidate>
<tr>
<div class="panel2">
<main class="content">
<td><input name="hanis" id="hanis" type="text" value="<?php echo
$row['email']?>" autofocus /></td>
<td><button type="button" class="btn btn-success btn-block"
name="hanis" id="hanis" onclick="hanisdata()" value="<?php echo
$row['email']?>" ><?php echo $row['email']?></button><</td>
</main></div>
</div>
</div>
</form>
<?php } ?>
</tr>
<script type="text/javascript">
function hanisdata() {
var hanis=$("hanis").val();
alert(hanis);
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "hanis.php",
data: {hanis:hanis},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
NOTE :- Don't use same id for elements
You can get values by passing this with onclick function like onclick="hanisdata(this)"
Example
<button type="button" class="btn btn-success btn-block"
name="hanis" id="hanis" onclick="hanisdata(this)" value="<?php echo
$row['email']?>" ><?php echo $row['email']?></button>
Then you can get specific element in js and then can find parent and search for input field in that like below example.
JS CODE
<script type="text/javascript">
function hanisdata(el) {
var hanis=$(el).parent().find("input").val();
alert(hanis);
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "hanis.php",
data: {hanis:hanis},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
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();
}
?>
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 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 have the following script :
<script>
$(document).ready(function() {
$('#edit').click(function (){
//get
employee_id = $('#employee_id').val();
alert(employee_id);
html='';
$.ajax({
type: "GET",
url: "<?php echo base_url();?>administrator/admin/get_employee_details/"+employee_id,
dataType: "json",
success: function(response) {
console.log(response);
$( '#fname' ).val(response[0].f_name);
alert(response[0].amount);
$( '#sname' ).val(response[0].l_name);
$( '#lname' ).val(response[0].other_name);
$( '#expiry_date' ).val(response[0].id_no);
$( '#quantity_available').val(response[0].dob)
$( '#gender' ).val(response[0].gender);
$( '#maritalstatus').val(response[0].marital_status)
$( '#sex' ).val(response[0].gender);
},
error: function(data){
}
})
});
});
</script>
The script is supposed pick the employee_id value from the table below :
<tbody>
<?php foreach($employee_details as $employee ):?>
<tr class="odd gradeX">
<td><?php echo $employee['employee_name'];?></td>
<td ><?php echo $employee['id_no'];?></td>
<td><?php echo $employee['dob'];?></td>
<td><?php echo $employee['gender'];?></td>
<td ><?php echo $employee['marital_status'];?></td>
<td><?php echo $employee['phone_no'];?></td>
<td><?php echo $employee['email'];?></td>
<td ><?php echo $employee['date_added'];?></td>
<td><?php echo $employee['residence'];?></td>
<td ><?php echo $employee['next_of_kin_name'];?></td>
<td><?php echo $employee['next_of_kin_relation'];?></td>
<td><?php echo $employee['next_of_kin_phone_no'];?></td>
<td ><?php echo $employee['is_active'];?></td>
<td><?php echo $employee['department_name'];?></td>
<td><?php echo $employee['employee_class'];?></td>
<td><a class="edit" href="#edit_details" id="edit">Edit </a></td>
<td> <a class="delete" href="#delete_details" id="delete" > Delete Employee</a></td>
<input type="text" name="employee_id" id="employee_id" value="<?php echo $employee['employee_id'];?>"/>
</tr>
<?php endforeach;?>
</tbody>
which is a hidden text field (employee_id) in the table when I click the Edit button. But when I click the link , I get an empty result with no employee_id yet I can see the employee id in the text box. How can I get the employee id from the text box for each specific row?
Id of an element must unique, so inside the loop use class instead of id, also move the employee_id field to a td element
<td>
<a class="edit" href="#edit_details">Edit </a>
</td>
<td>
<a class="delete" href="#delete_details" > Delete Employee</a>
<input type="text" name="employee_id" value="<?php echo $employee['employee_id'];?>" />
</td>
then
$(document).ready(function () {
$('.edit').click(function () {
//get
var employee_id = $(this).closest('tr').find('input[name="employee_id"]').val();
alert(employee_id);
html = '';
$.ajax({
type: "GET",
url: "<?php echo base_url();?>administrator/admin/get_employee_details/" + employee_id,
dataType: "json",
success: function (response) {
console.log(response);
$('#fname').val(response[0].f_name);
alert(response[0].amount);
$('#sname').val(response[0].l_name);
$('#lname').val(response[0].other_name);
$('#expiry_date').val(response[0].id_no);
$('#quantity_available').val(response[0].dob)
$('#gender').val(response[0].gender);
$('#maritalstatus').val(response[0].marital_status)
$('#sex').val(response[0].gender);
},
error: function (data) {
}
})
});
});
The id attribute must be unique in your web page. You can't have 2 elements with the same id.
So for your links and your inputs, you must generate a different id for each row. For example you can try id="employee_id-<?php echo $employee['employee_id'];?>".
But you can keep the same classes for each link and input, and use it in your javascript script code.
Then you must change your code :
$('.edit').click(function() {
var employee_id = this.closest('tr').find('.employee_id').val();
});
Use class attribute instead of id because id cant be repeated.
<input type="text" name="employee_id" class="employee_id" value="<?php echo $employee['employee_id'];?>"/>
$('.edit').click(function() {
var id = this.closest('tr').find('input.employee_id').val();
});
In Id you will be able to get employee id