I am trying to post the 'ID' from my html table to delete the row from the SQL database when the delete button is click. So far it would appear the POST is not working but the PHP code is.
Here is the JavaScript code which takes the selected table rows value from the first columns (ID) when I select it, and on pressing the delete button a message box displays the ID (this works fine so it would appear it is reading the value). The next part then displays a message box confirming the delete, which on clicking OK does nothing.
JavaScript
$(function(){
$("#tblAssets tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
});
$('#btnDelete').click(function(e){
var value = $("#tblAssets tr.selected td:first").html();
alert(value);
if (confirm("Are you sure you want to delete this asset?")) {
$.ajax({
type : "POST",
url : "inventory_hardware_delete.php",
data : value;
success : function() {
}
});
}
});
});
And here is the PHP code. When I manually adjust $value to equal an ID in my database table it works and deletes the row.
$value = $_POST['value'];
$sql = "DELETE FROM [Assets].[dbo].[Hardware] WHERE [ID] = $value";
$result = sqlsrv_query( $conn, $sql);
Thanks
this line is wrong
data : value;
Try this
data : {value:value},
^ not semi colon
You are passing value without parameter. Add parameter:
$(function(){
$("#tblAssets tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
});
$('#btnDelete').click(function(e){
var data = {
"value": $("#tblAssets tr.selected td:first").html();
};
if (confirm("Are you sure you want to delete this asset?")) {
$.ajax({
type : "POST",
url : "inventory_hardware_delete.php",
data : $.param(data);
success : function() {
}
});
}
});
});
or your ajax data should be like this:
data: "value="+$("#tblAssets tr.selected td:first").html();
Moreover you cannot use ; here:
data : value;
it should be ,
data : "value"+value,//pass value with the name:ie value=10 . replace the ajax part alone as given below
$.ajax({
type : "POST",
url : "inventory_hardware_delete.php",
data : "value"+value,//
success : function() {
}
});
You didn't create an object and passed the variable on the fly directly.
var value = $("#tblAssets tr.selected td:first").html();
//alert(value);
if (confirm("Are you sure you want to delete this asset?")) {
var dataValue = {
theValue : value // You have to create an object here
};
$.ajax({
type : "POST",
url : "inventory_hardware_delete.php",
data : dataValue, // pass the object here
success : function() {
}
});
}
On the server side:
$value = $_POST['theValue'];
Try this one.
Related
Project Link: https://databasetable-net.000webhostapp.com/
This following code correctly deletes a row in a table:
$('#example').on('click', '.delete_btn', function () {
var row = $(this).closest('tr');
var data = table.row( row ).data().delete;
console.log(data);
alert("delete_btn clicked");
row.remove();
});
However, it is not permately deleting the row. If you refresh the page, the row that got 'deleted' still exists. I believe this is because I am not deleting the row out of the database. Normally in php you safely remove a row in a database with something like this:
id = mysqli_real_escape_string($con, $_GET['del']);
$stmt = $con->prepare("DELETE FROM employees WHERE id = ? LIMIT 1");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
header('location: index.php');
EDIT: Revised Code Index.php:
(document).ready(function() {
var asc = true;
var table = $('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "server.php",
"type": "POST",
},
//http://live.datatables.net/xijecupo/1/edit
columnDefs: [{
targets: -1,
defaultContent: '<button type="button" class="delete_btn">Delete</button>'
}],
rowGroup: {
dataSrc: 1
}
});
$(function(){
$(document).on('click','.delete_btn',function(){
var del_id= $(this).closest('tr');
var ele = $(this).parent().parent(); //removed the "$" from the ele variable. It's a js variable.
console.log(del_id);
$.ajax({
type:'POST',
url:'delete.php',
dataType: 'json', //This says I'm expecting a response that is json encoded.
data: { 'del_id' : del_id},
success: function(data){ //data is an json encoded array.
console.log('Data: ' + data); //Going to display whats in data so you can see whats going on.
if(data['success']){ //You are checking for true/false not yes or no.
console.log('You successfully deleted the row.');
alert("delete btn clicked");
ele.remove();
}else{
console.log('The row was not deleted.');
}
}
});
});
}); //http://jsfiddle.net/zfohLL0a/
}); //end doc ready
delete.php code:
$del_id = $_POST['del_id'];
$stmt = $conn->prepare("DELETE FROM employees WHERE id = ?"); //LIMIT 1
$stmt->bind_param('i', $del_id);
$confirmDelete = $stmt->execute();
$array['success'] = FALSE; //Initialize the success parameter as false.
if($confirmDelete){ //Check to see if there was an affected row.
$array['success'] = TRUE;
}
echo json_encode($array);
?>
Partial Solution: Sample format how to setup the ajax. You have to start off by using the datatables.net "ajax": method for the original server.php. But then after that you use the normal $.ajax methods for the add.php, delete.php, etc. It is confusing because you use two different syntax for ajax. Easiest to just look at the sample link. Youtube video for same code
Another helpful link that discusses sending info to and from the ajax/json are one two three Four
Updated answer using your latest updated code.
JS
$(function(){
$(document).on('click','.delete_btn',function(){
var del_id= $(this).closest('tr');
var ele = $(this).parent().parent(); //removed the "$" from the ele variable. It's a js variable.
console.log(del_id);
$.ajax({
type:'POST',
url:'delete.php',
dataType: 'json', //This says I'm expecting a response that is json encoded.
data: { //Set up your post data as an array of key value pairs.
'del_id' : del_id
},
success: function(data){ //data is an json encoded array.
console.log('Data: ' + data); //Going to display whats in data so you can see whats going on.
if(data['success']){ //You are checking for true/false not yes or no.
console.log('You successfully deleted the row.');
ele.fadeOut().remove();
}else{
console.log('The row was not deleted.');
}
}
});
});
});
delete.php
$del_id = $_POST['del_id'];
$stmt = $con->prepare("DELETE FROM employees WHERE id = ?"); //LIMIT 1
$stmt->bind_param('i', $del_id);
$confirmDelete = $stmt->execute();
$array['success'] = FALSE; //Initialize the success parameter as false.
if($confirmDelete){ //Check to see if there was an affected row.
$array['success'] = TRUE;
}
echo json_encode($array); //Your ajax is setup to expect a json response.
//json_encode the $array and echo it out. You have to do this.
//When you "echo" out a value, that is what the server is going to submit back to the ajax function.
//If you do not do this, the ajax script will not recieve a response from the delete.php page.
This code should work for you.
In addition to Joesph's response who was extremely helpful:
"The console shows "Uncaught RangeError: Maximum call stack size exceeded". It looks as though the Ajax call isn't being issued (nothing is showing on the network tab) - so it must be when creating the request. I suspect I may need to JSON.stringify your del_id."
Someone suggested this:
"The main stack problem is caused by var edit_id = $(this).closest('tr'); . You try to send that whole jQuery object as data in the ajax. Then jQuery can't serialize it internally and throws a fit
You probably want some property like ID or a data attribute from that row to send (not clear what expectations are)."
Please post if you have any recommendations. I will edit in any finalized code solution soon.
//ADDING NEW ITEM INTO THE ITEM TABLE
$(document).on('submit', '#product_form', function(event){
event.preventDefault();
btn_action="add_pricelvl"; //Set variable to call the add new item
var valdata = $(this).serialize(); //Array with field value
var tax = $('#item_tax').val(); //checkbox tax
var taxvalue = $('#item_taxvalue').val(); //inputbox tax
var tabledets = it_det //Read the detail table
.rows()
.data();
var arr1=[];
var i=0;
//Put the datatable rows in the array
for (i=0; i<tabledets.length; i++){
arr1[i]=tabledets.rows(i).data();
}
//call ajax function and send variable to php file.
$.ajax({
url:'item_action.php',
method:"POST",
data:{
btn_action:btn_action,
valdata:valdata,
tax:tax,
taxvalue:taxvalue,
arr1:arr1
},
success : function(data)
{
$('#product_form')[0].reset();
$('#productModal').modal('hide');
$('#alert_action').fadeIn().html('<div class="alert alert-success">'+data+'</div>');
$('#action').attr('disabled', false);
$('#item_data').DataTable().ajax.reload();
},
error : function () {
$('<div>').html('Found an error!');
}
})
});
That's my java code and I'm trying to call a php page and save all data in my DB. I got an error:
TypeError: 'insertCell' called on an object that does not implement interface HTMLTableRowElement.
That's happening when I insert data into the table "it_det"
Look the picture:
If I don't insert new rows into the table I don't get error!
What's wrong with that? Why I'm getting this error???
I found the solution changing the "processData" key to false
$.ajax({
processData: false, //The default value of ProcessData is true so changing in false I don't get any error.
url:'item_action.php',
method:"POST",
i'm trying to post a form containing an input text, a textarea, and 14 checkbox with ajax. The idea is to insert some data according to the number of checked checkbox into table dbdata.
Here is the script.js :
$(document).on('click', '#save', function(event) {
//action
var url = "aksi.php";
//an input text
var v_id = $('input:text[name=id]').val();
//a textarea
var v_note = $('#note').val();
//some checkboxes
var v_checkbox =[]
$("input[name='checkbox[]']:checked").each(function ()
{
v_checkbox.push(parseInt($(this).val()));
});
//ajax
$.ajax({
url: url,
type: "POST",
data: {id: v_id,note: v_note,checkbox:v_checkbox },
success: function (data, status){
alert("success!")
},
error: function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
});
This is the aksi.php :
require "../../config/db.php";
$id=$_POST['id'];
$checkbox= $_POST['checkbox'];
$note=$_POST['note'];
foreach ($checkbox as $key => $check_box) {
mysqli_query($con,"INSERT INTO dbdata(id, checkbox, note) VALUES($id, $check_box, '$note')");
}
The problem is the data never posted. The ajax thrown error (readyState=0, status=0) and data not inserted. The url also changed to :
index.php?checkbox[]=3&checkbox[]=4&checkbox[]=5
depend on which checkbox are checked. Any idea?
Can you put one echo statement at the last in php file for resolving the error issue. like
echo 1;
Update the first line like this if save is the submit button:
$(document).on('click', '#save', function(event) {
event.preventDefault();
.....
});
For resolving the db insertion issue, try include the full path of the required file instead of relative path.
i am trying to dynamically have javascript object properties to send through ajax..
Here is what i have done..
var checkBoxName = $(this).attr('name');
var postData = {
Module: ModuleID,
Group:GroupID
};
if($(this).is(":checked")){
postData.checkBoxName = 1;
}else{
postData.checkBoxName = 0;
}
$.ajax({
url: "<?php echo base_url(); ?>user_site/user_group_add_pri/updatePrivilege",
data:postData,
type: "POST",
success: function (output) {
console.log(output);
}
i have multiple checkboxes. every checkbox has different name so what i am trying to do is post data to controller with checkbox name and its value..
but instead it is sending checkBoxName for all checkboxes...
i mean CheckBoxName is a variable but when i did used it like this cuz i thought it would send its value but it is not sending,
i tried like this postData.checkBoxName = but instead of value of variable it is sending as Text??
=-=-=-=-=-=-=-=-=-=--=-=-=-=-=
Update:
The event Occurs when checkbox value is changed.
$("input[type='checkbox']").on('change',function(e){
///Above Code Inside Here
}
If I understand right, I might have an idea.
You can do a loop through all your checkboxes and check if they are checked or not. Then push it into a tab and send through ajax :
var infoCb = new Array();
$('input[type=checkbox]').each(function(){
var tempArray = {
'nameOfCb' : $(this).attr('name'),
'value' : $(this).attr('checked')
}
infoCb.push(tempArray);
});
And then send it via Ajax.
I'm trying to print a calendar using php but struggle figuring out how to change the month displayed with ajax
I have two buttons in tag whose value is "+1" and "-1" respectively with a class="selectMonth"
<button class="selectMonth" name="selectMonth" value="-1">previous</button>
<button class="selectMonth" name="selectMonth" value="+1">next</button>
This is my ajax code:
$(".selectMonth").on("click", function(){
$.ajax({
url : "index.php",
type : "POST",
data : {selectMonth : this.value},
success : function(){
alert("success!");
}
});
});
and in my index.php I have
<?php
if(!isset($_POST["selectMonth"]))
$_SESSION["date"] = time();
else
{
$selectMonth = $_POST["selectMonth"];
$_SESSION["date"] = strtotime($selectMonth . 'month');
}
var_dump($_POST["selectMonth"]);
$date = $_SESSION["date"];
print_calendar($date);
?>
After I click one of the buttons, I can get the alert message but not the $_POST variable and what is var_dump is always NULL
Could anybody find out the mistake for me?
I'm still learning ajax.
Thank you very much!
try below line of code :
data : {'selectMonth' : $(this).val()},
OR
data : {'selectMonth' : $(this).attr('value')},
Try
$(".selectMonth").on("click", function(){
var inputVal = $(this).attr('value');
$.ajax({
url : "index.php",
type : "POST",
data : {selectMonth : inputVal},
success : function(){
alert("success!");
}
});
});
Instead of
data : {selectMonth : this.value}
try
data : {selectMonth : this.val()}