Delete by AJAX request - php

I have a button which call this AJAX request to delete record.
How could I show/handle mysql errors correctly like:
Error: Table 'supplier_contacts' doesn't exist
// DELETE
$('.delete-btn').click(function () {
// Confirm
if (!confirm('Are you sure want to delete this row?')) {
return false;
}
// id need to delete
var contact_id = $(this).attr('contact_id');
// Current button
var obj = this;
// Delete by ajax request
$.ajax({
type: "post",
dataType: "text",
url: 'suppliers_sql.inc.php?a=delete_contact',
data: {
contact_id: contact_id
},
success: function (result) {
$(obj).parent().parent().remove();
window.location.assign('suppliers_details.php?id=<? echo $supplier_id ?>&m=success');
}
});
});
SQL QUERY of suppliers_sql.inc.php ? a = delete_contact
// --------------------------------------------------------------------------------------------
// DELETE CONTACT
// --------------------------------------------------------------------------------------------
if ($_REQUEST['a'] == "delete_contact") {
$contact_id = $_POST['contact_id'];
$sql_contact = "DELETE FROM supplier_contacts WHERE contact_id = $contact_id";
if (mysqli_query($mysqli, $sql_contact)) {
mysqli_close($mysqli);
//header("Location: suppliers_details.php?id=$supplier_id&m=success");
exit;
} else {
echo "Error: " .$sql_contact. "<br>" .mysqli_error($mysqli);
mysqli_close($mysqli);
exit;
}
}

As you are echoing something if there is an error you can display it in your success.
$.ajax({
type : "post",
dataType : "text",
url : 'suppliers_sql.inc.php?a=delete_contact',
data : {
contact_id : contact_id
},
success : function(result){
if(result)
{
//Your error
alert(result);
}
else
{
//all good
$(obj).parent().parent().remove();
window.location.assign('suppliers_details.php?id=<? echo $supplier_id ?>&m=success');
}
}
});

Related

405 (Method Not Allowed) (POST) method with ajax jQuery

im trying to send some data through ajax jQuery to a php file with POST but i keep getting POST 405 Method Not Allowed error, any ideas to solve this issue will be appreciated, heres the function that makes the call
function manageData(key) {
var name = $("#countryName");
var abbrev = $("#countryAbbrev");
var desc = $("#countryDesc");
if (isNotEmpty(name) && isNotEmpty(abbrev) && isNotEmpty(desc)) {
$.ajax({
url: 'http://127.0.0.1:5500/ajax.php',
method: 'POST',
dataType: 'text',
data: {
key: key,
name: name.val(),
abbrev: abbrev.val(),
desc: desc.val()
},
success: function (response) {
alert(response);
}
});
}
}
and here is the ajax.php file code
<?php
if (isset($_POST['key'])) {
$conn = new mysqli(host:'localhost', username:'root', passwd:'root',
dbname:'mysqldatamanager');
$name = $conn->real_escape_string($_POST['name']);
$abbrev = $conn->real_escape_string($_POST['abbrev']);
$desc = $conn->real_escape_string($_POST['desc']);
if($_POST['key'] == 'addNew') {
$sql = $conn->query(query:"SELECT id FROM country WHERE
countryName = '$name'");
if ($sql->num_rows > 0) {
exit("Country already exists!");
} else {
$conn->query("INSERT INTO country (countryName,
countryAbbrev, countryDesc) VALUES ('$name', '$abbrev',
'$desc')");
exit("Country has been added succesfully!");
}
}
}
?>
Please try below code.
function manageData(key) {
var name = $("#countryName");
var abbrev = $("#countryAbbrev");
var desc = $("#countryDesc");
if (isNotEmpty(name) && isNotEmpty(abbrev) && isNotEmpty(desc)) {
$.ajax({
url: 'http://localhost/ajax.php',
type: "POST",
data: {
key: key,
name: name.val(),
abbrev: abbrev.val(),
desc: desc.val()
},
success: function (response) {
alert(response);
}
});
}
}

Code igniter MVC ajax delete not working

why is this failing.
my view code
function Dispose(id){
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url:"<?php echo site_url('Login/ajax_delete')?>" ,
type: 'post',
data: {'id' : id},
success: function () {
alert('ajax success');
},
error: function () {
alert('ajax failure');
}
});
}
}
controller code:
public function ajax_delete()
{
$id = $this->input->post('id');
$this->mod->delete_by_id($id);
}
model code:
public function delete_by_id($id)
{
$this->db->where('id', $id);
$this->db->delete('chemicalBottleInfo');
}
what i want to happen is to delete the item from chemicalbottleinfo
Your are passing id was wrong should not be quotes
function Dispose(id){
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url:"<?php echo site_url('Login/ajax_delete')?>" ,
type: 'post',
data: {id : id},
success: function () {
alert('ajax success');
},
error: function () {
alert('ajax failure');
}
});
}
}
Another way:
Adding a check before deleting the id in the table.
Javascript:
function Dispose(id){
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url:"<?php echo site_url('Login/ajax_delete/'+id)?>" ,
success: function () {
alert('ajax success');
},
error: function () {
alert('ajax failure');
}
});
}
}
Controller:
public function ajax_delete($id= '')
{
$id = $this->input->post('id');
if($id != ''){
$response = $this->usrExist($id, 'chemicalBottleInfo');
}
if($response == 1){
$this->mod->delete_by_id($id);
}
}
public function usrchk($id,$tableName) {
$qry = "SELECT count(*) as cnt from ".tableName." where id= ?";
$res = $this->db->query($qry,array($id))->result();
if ($res[0]->cnt > 0) {
return 1;
} else {
return 0;
}
}

Update MySQL if checkbox Unchecked

I am using the script found here to update my database if a box is checked.
https://stackoverflow.com/posts/4592766/revisions
It works if I check an unchecked box.
However, I can't seem to get it working if I uncheck a checked box. It will not update the database.
Here is the modified code:
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var isSel = this.checked;
var isNotSel = this.unchecked; //added
$.ajax({
url: 'file.php',
type: 'POST',
dataType: 'json',
data: {
id : this.id,
isSelected : isSel,
isNotSelected : isNotSel // added
},
success: function(data) {
alert('updated');
},
error: function() {
alert('error');
}
});
});
});
This is the code showing the checkboxes (created from database):
if($status == 'pending')
{ echo '<input type="checkbox" name="status" id='.$submission_id.' >' .
$task_name . '<br>'; }
if($status == 'done')
{ echo '<input type="checkbox" name="status" id='.$submission_id.' checked>'
. $task_name . '<br>'; }
Here is the code for file.php
if ($_POST && isset($_POST['isSelected'])) {
$sql = 'UPDATE ft_form_53 SET status = "done" WHERE submission_id = ' . $_POST['id'];
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
if ($_POST && isset($_POST['isNotSelected'])) {
$sql = 'UPDATE ft_form_53 SET status = "pending" WHERE submission_id = ' . $_POST['id'];
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
No error message is thrown. Any ideas?
Change
var isNotSel = this.unchecked;
to
var isNotSel = !isSel;
or
var isNotSel = !this.checked;
Checkboxes don't have an unchecked property. They have a boolean checked property (true if checked, false if not). And you've already grabbed that into isSel, so...
Got it working. Thanks to shehary for the click to change modification and to T.J. Crowder for the !this.checked tip. I ended up using two separate scripts but it works :) Thanks again to all!
The one below is for uncheck.
$(document).ready(function() {
$("input[type=checkbox]").change(function() {
var isNotSel = !this.checked;
$.ajax({
url: 'file.php',
type: 'POST',
dataType: 'json',
data: {
id : this.id,
isNotSelected : isNotSel
},
success: function(data) {
alert('updated');
},
error: function() {
alert('error');
}
});
});
});

how to fetch mysql data using ajax when one input is filled using function.php

mysql table
|order_no |order_name |
| -------- |------------|
| 43423 | abc |
??????????????????????????
now my question is how do i use ajax to fetch the order name and city when i order number ? any help is appreciated..
I have a code here:
ValidateForm.js
var searchTimeout; //Timer to wait a little before fetching the data
$("#order_numbr").keyup(function() {
searchKey = this.value;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
getUsers(searchKey);
}, 400); //If the key isn't pressed 400 ms, we fetch the data
});
function getUsers(searchKey) {
$.ajax({
type : "POST",
async: false,
data : "action=checkOrdrNum",
url : ajaxurl,
dataType:"json",
success: function(data) {
if(data.status) {
$("#ur_name1").val(data.userData.order_name);
}
}
}"This order number does not exist");
}
And ofcourse the function.php file:
add_action('wp_ajax_nopriv_checkOrdrNum','checkOrdrNum');
add_action('wp_ajax_checkOrdrNum','checkOrdrNum');
function checkOrdrNum(){
global $wpdb,$current_user;
$response = Array();
$response['status'] = false;
$query = mysql_query("SELECT `order_name` FROM `art_work_history` WHERE `order_no` LIKE '%".$_POST['value']."%' LIMIT 1"); //Or you can use = instead of LIKE if you need a more strickt search
if(mysql_num_rows($query)) {
$userData = mysql_fetch_assoc($query);
$response['userData'] = $userData;
$response['status'] = true;
}
echo json_encode($response);
}
U need to pass input value to the ajax
I thnk that was the only thing missing
function getUsers(searchKey) {
$.ajax({
type : "POST",
async: false,
data : "action=checkOrdrNum",
url : ajaxurl,
dataType:"json",
data: {value: searchKey}, // this is the line missing
success: function(data) {
if(data.status) {
$("#ur_name1").val(data.userData.order_name);
}
}
});
}

How to return an error callback in php?

I was wondering if I can return an error callback back to my jquery from my php page that I created, which will then display an alert based upon the actions that happen in my php page. I tried creating a header with a 404 error but that didn't seem to work.
Sample JQuery Code:
$(document).ready(function()
{
var messageid= '12233122abdbc';
var url = 'https://mail.google.com/mail/u/0/#all/' + messageid;
var encodedurl = encodeURIComponent(url);
var emailSubject = 'Testing123';
var fromName = 'email#emailtest.com';
var dataValues = "subject=" + emailSubject + "&url=" + encodedurl + "&from=" + fromName + "&messageID=" + messageid;
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function() {
alert('ERROR - MessageID Duplicate')
}
});
return false;
});
});
Sample PHP Code aka somepage.php:
<?php
include_once('test1.php');
include_once('test2.php');
if(isset($_GET['subject']))
{
$subject=$_GET['subject'];
}
else
{
$subject="";
}
if(isset($_GET['url']))
{
$url=$_GET['url'];
}
else
{
$url="";
}
if(isset($_GET['from']))
{
$from=$_GET['from'];
}
else
{
$from="";
}
if(isset($_GET['messageID']))
{
$messageID = $_GET['messageID'];
}
else
{
$messageID="";
}
$stoqbq = new test2($from, $messageID);
$msgID = new stoqbq->getMessageID();
if($msgID = $messageID)
{
header("HTTP/1.0 404 Not Found");
exit;
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
}
?>
-EDIT-
If you get the invalid label message when using json this is what I did to fix this problem:
Server Side PHP Code Part-
if($msgID == $messageID)
{
$response["success"] = "Error: Message Already In Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new SendToQuickbase($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
$response["success"] = "Success: Sent To Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
Client Side JQuery Part-
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
cache: false,
contentType: "application/json",
dataType: "json",
url: "http://somepage.php?&callback=?",
success: function(response){
alert(response.success);
}
});
return false;
});
You can a return a JSON response from your PHP with a success boolean.
if($msgID = $messageID)
{
echo json_encode(array('success' => false));
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
echo json_encode(array('success' => true));
}
and in your Javascript:
$.ajax({
type: 'GET',
dataType: 'json',
data: dataValues,
url: 'http://somepage.php',
success: function(response){
if(response.success) {
alert('Success');
}
else {
alert('Failure');
}
}
});
There is an accepted q/a with the same thing: How to get the jQuery $.ajax error response text?
Basically you need to grab the response message from the error callback function:
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
});

Categories