If I console.log the ID out after I am meant to delete the record, the correct ID displays in console. So, it seems that it is connected up properly but doesn't actually delete a record from my database. I cannot figure this out but it's probably something obvious.
JS
<script type="text/javascript">
$(document).ready(function() {
$('.table-row').on('click', function (e) {
e.preventDefault();
var $otId = $(this).data('ot-id');
swal({
title: 'Are you sure?',
text: "You won't be able to undo this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#FB404B',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
closeOnCancel: false
}, function (isConfirm) {
if (isConfirm) {
$.ajax({
type: 'post',
url: 'functions/delete-ot-request.php',
data: {otId: $otId},
success: function (result) {
// window.location.href = 'delete-ot.php';
console.log($otId);
},
});
} else {
swal("Cancelled", "Maybe next time then.", "error");
}
});
});
});
</script>
PHP
if(isset($_POST['otId'])) {
$stmt = $link->prepare("DELETE FROM `ot_request` WHERE `id` = ? LIMIT 1");
$stmt->bind_param("i", $_POST['otId']);
$stmt->execute();
$stmt->close();
}
This is the html table row that holds the id:
<tr class="table-row" data-ot-id="{$id}"></tr>
Your console.log($otId); reports the id value you previously sent, not a data coming back from the server side.
Hence this output attests only that the ajax process was successful, not the server job, which is likely what turns wrong for some reason.
So you should look for errors at the server side, starting with sending back some execution trace:
if(isset($_POST['otId'])) {
try {
$stmt = $link->prepare("DELETE FROM `ot_request` WHERE `id` = ? LIMIT 1");
$stmt->bind_param("i", $_POST['otId']);
$stmt->execute();
$stmt->close();
echo 'otId "' . $_POST['otId'] . '" processed';
} catch(PDOException $e) {
echo $e->getMessage;
}
} else {
echo 'No otId found';
}
And modifying your Javascript so you output this trace:
success: function (result) {
console.log(result);
}
Related
I'm trying to get a value from my database and then run an update using sweet alert pop-up but it is not working. The alert seem to pop-up and once the value is entered, it displays the value entered but not working. below is my actual ajax code:
viewproduct.php
<script>
$(document).ready(function() {
$('.btnupdatestock').click(function() {
var id = $(this).attr("id");
//var new_stock = $(this).val();
swal("Add Stock:", {
content: "input",
})
.then((updateStock) => {
$.ajax({
type: 'POST',
url: 'stock-in.php',
data:{
stock_up: updateStock,
},
success: function(data){
swal(`Updated: ${updateStock}`);
},
error: function(data){
swal(`Error updating: ${updateStock}`);
}
});
});
});
});
</script>
the above method was designed to trigger sql in stock-in.php and the code in stock-in.php is below:
<?php
include_once'connectdb.php';
if($_SESSION['useremail']=="" OR $_SESSION['role']=="Admin"){
header('location:index.php');
}
$idd=$_GET['id'];
$select=$pdo->prepare("select * from tbl_product where pid=$idd");
$select->execute();
while($row=$select->fetch(PDO::FETCH_OBJ)){
$productName = $row['pname'];
$oldstock = $row['pstock'];
//$id=$_POST['uid'];
$stockup=$_POST['stock_up'];
alert('I clicked');
$new_stock = $oldstock + $stockup;
$sql="UPDATE `tbl_product` SET `pstock` = ? WHERE pid= ? ";
$update=$pdo->prepare($sql);
$update->execute([$new_stock, $idd]);
if($result){
echo'Stock updated!';
}else{
echo'Error in updating stock';
}
}
?>
below is a picture of my UI that shows pop-up but it's not updating.
This is what I intend to do: If a user clicks on update and enters a value say 50, it should retrieve the old stock (database, say 100) and add to the new stock (value entered, say 50) and then update the database with 150. I am stuck here and any help would be appreciated. Thanks.
$(document).ready(function() {
$('.btnupdatestock').click(function() {
swal("Add Stock:", {
buttons: true,
closeModal: true,
content: "input",
}).then((updateStock) => {
if (updateStock === "") {
swal("You need to write something!");
return false
}else{
$.ajax({
type: 'POST',
url: 'stock-in.php',
data:{
stock_up: updateStock
<?php
echo ', id: '.$row->pid.' '
?>
<?php
echo ', oldstock: '.$row->pstock.' '
?>
},
success: function(data){swal(`Updated: ${updateStock}`);},
error: function(data){swal(`Error updating: ${updateStock}`);}
});
}
});
});
});
The major issue I had was I didn't make the SQL query global at the top of my page and then applied '.$row->pid.'
Need help in converting PDO array execution to mysqli statements. This executes for an AJAX POST call for deleting a particular id from database with SWAL function.
<?php
require_once 'connectivity.php';
$response = array();
if ($_POST['delete']) {
$pid = intval($_POST['delete']);
$query = "DELETE FROM students WHERE id=$pid";
$stmt = mysqli_query($query,$connect);
$stmt->execute(array(':pid'=>$pid));
if ($stmt) {
$response['status'] = 'success';
$response['message'] = 'Student Deleted Successfully ...';
} else {
$response['status'] = 'error';
$response['message'] = 'Unable to delete ...';
}
echo json_encode($response);
}
?>
This is the consecutive swal function which is to be executed once the delete button clicked.
<script>
$(document).ready(function(){
$(document).on('click', '#deleteid', function(e){
var productId = $(this).data('id');
SwalDelete(productId);
e.preventDefault();
});
});
function SwalDelete(productId){
swal({
title: 'Are you sure?',
text: "It will be deleted permanently!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
showLoaderOnConfirm: true,
preConfirm: function() {
return new Promise(function(resolve) {
$.ajax({
url: 'delete.php',
type: 'POST',
data: {'delete' : productId}
})
.done(function(response){
swal('Deleted!', response.message, response.status);
readDetails();
})
.fail(function(){
swal('Oops...', 'Something went wrong with ajax !', 'error');
window.location.reload(true);
});
});
},
allowOutsideClick: false
});
}
function readDetails(){
window.location.reload(true);
}
I am beginner in study AJAX.
here is PHP for post action of my form, but somehow it always return false.
<?php
session_start();
include"../connection/sambung.php";
$us=$_SESSION['username'];
if ($_SERVER['REQUEST_METHOD'] == 'POST') { //halaman ini harus dipanggil melalui post
$id = $_POST["id"];
$code = $_POST["code"];
$act = $_POST["act"];
switch($act){
//tambah data
case "insert":$sql="INSERT INTO karyawan(nip,nama)VALUES('".$nip."','".$nama."')";$i='1';break;
//edit data
case "validate":$sql="UPDATE member SET validasi=1 WHERE id_member ='".$id."' and kode_member='".$code."'";$i='2';break;
//hapus data
case "delete":$sql="DELETE FROM karyawan WHERE nip = '".$nip."'";$i='2';break;
}
//eksekusi sql
$kueri = mysql_query($sql);
//tampilkan hasil
if($i=='1'){
if(mysql_num_rows($kueri)){echo "success";}
}
else if($i=='2'){
if (mysql_affected_rows($kueri)){echo "success";}
}
else{
echo "failed";
}
}else{
echo "This link can't run directly.";
}
?>
and the AJAX configuration as follow:
$( "#dialog-validate" ).dialog({
autoOpen: false,
height: 200,
width: 350,
modal: true,
buttons: {
"Validate": function() {
var
aid = $("#idedit").html();
acode = $("input#codeedit").val();
aact= 'validate';
$("#waiting").show();
$.ajax({
type: "POST",
url: "applicant/check.php",
data: {"id":aid,"code":acode,"act":aact},
timeout: 3000,
beforeSend: function(){},
complete: function(){},
cache: false,
success: function(result){
if (result=='success'){
//ubah isi data table sesuai dengan perubahan yang terjadi
objRow.find(".valcell").html("Yes");
$("#waiting").hide();
}else{alert('gagal simpan data');$("#waiting").hide();}
},
error: function(error){$("#waiting").hide();alert(error);}
}
);
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
what I need is how to make
success: function(result){
if (result=='success'){
result false, I have been changing it many times, PHP or AJAX error? please help
It looks like you're checking for an error code inside your success function. If your script returns an HTTP 200 OK header, success will be invoked. Try setting an error header so that your error function is invoked.
This doesn't answer your question exactly I'm afraid, but it's going to make your code easier to read and could very well solve your problem.
I'm using in the same page a validation engine with date picker.
Datepicker: http://jqueryui.com/demos/datepicker/
Validationengine: http://www.position-relative.net/creation/formValidator/demos/demoValidators.html
I've added a jQuery.noConflict(); to make it work (at the beginning of the code).
Now, I need to make my insert through a PHP file, but without refreshing the page, and by displaying an error message in the same bubble of validationEngine (for example when the email is already registered in the BDD).
should I import jQuery to make my insert in the same page
without causing conflicts, or can I use one on the query already used
for the same purpose?
How do I display a server response through the validationEngine?
My code is the following one.
$(".btn_newsletter").live('click', function() {
$.ajax(
{
url: "php/functions/signin.php"+nomfichier,
success: function(data) {
if (data.check==0) {alert('Error : Sorry '); return false;}
if (data.check==1) {alert('yep!!!');
}
},
cache: false,
type: "POST",
dataType: 'json'
});
}
This is my PHP code.
$ip= $_SERVER["REMOTE_ADDR"];
$select = "select * from av_newsletter where email='".$_POST['email']."'";
$exist = $_BASE->query_array($select);
if ($exist) {
$check = "0";
}
else {
$ajout="INSERT INTO av_newsletter(id,sub_date,email,ip) VALUES (NULL,now(),'$email','$ip')";
$add=$_BASE->query($ajout);
if ($add) {
$check="1";
}
}
$return_arr["check"] = $check;
echo json_encode($return_arr);
It doesn't work; I've no alert, but also no errors.
If you are not tied in too deeply to your 'Validationengine' I would recommend using this one, is has served me well for years, it has support for making remote checks so you could do something like this:
$(document).ready(function(){
var save_options = {
success: userSaved, //callback function
url: '/users/save',
response: 'json',
method: 'post'
};
var validationObj = {
rules: {
name: "required",
email: {
email: true,
required: true,
remote: "/user/check_email/"
}
},
messages: {
name: "Please name yourself",
email: {
required: "Please enter your email address",
email: "Invalid email address",
remote: "Email already in use."
}
},
errorPlacement:function(error, element) {
error.appendTo( element.next() );
},
submitHandler: function(form) {
$(form).ajaxSubmit(save_options);
},
success:function(label) {
label.html(" ").addClass("checked");
}
};
});
And then on the PHP side at the '/users/check_email' endpoint the PHP does the following:
echo $emailExists ? json_encode(false) : json_encode(true);
Ok, before we spam the comments and get to far off topic, please execute this code which should get you started in getting it to work eventually.
$(".btn_newsletter").live('click',function() {
alert('clicked'); // click is executed
$.ajax({
url: "php/functions/signin.php"+nomfichier,
success: function(data) {
alert(data); // should alert the data
if(data.check==0){ alert('Error : Sorry '); return false; }
if(data.check==1){ alert('yep!!!'); }
},
error: function(request, status, error) {
alert('failed '+status);
},
cache: false,
type: "POST",
dataType: 'json'
});
});
it works :)
$(".btn_newsletter").live('click',function() {
var data ="email="+$('#email').val();
$.ajax({
url: "php/functions/signin.php"+"?"+data,
success: function(data) {
if(data.check=='1'){ alert('yep!!!'); }
if(data.check=='0'){ alert('Error : Sorry '); return false; }
},
cache: false,
type: "POST",
dataType: 'json'
});
});
and in my signin.php I catch the value of the input like this $email=$_REQUEST['email']
Thanks a lot! time for me to see about validation engine how to link this with :)
So this is my idea, I have a login jquery dialog on my homepage that blocks anyone from using the webpage (behind the login form dialog). I use ajax to submit the information entered to a php page which then checks if the username/password combo exists in the database. If it does, I return true and then close the dialog box (allowing access to the site).
How do I use ajax to check if my php script (from the executed page) returns true or false?
I was assuming the success/error options of the ajax function were checking this, but the below code doesnt seem to work.
$('.login').dialog({
closeOnEscape: false,
title: false,
modal: true,
width: 'auto',
show: {effect: "fade", duration: 1500},
title: 'Login',
buttons: {
"Login": function() {
$.ajax({
async: false,
type: 'POST',
url: 'sql/login.php',
success: function(){
alert( "Success!");
},
error: function(){
alert( "Failed!" );
},
dataType: "html"
});
}
}
});
$(".login").dialog().parents(".ui-dialog").find(".ui-dialog-titlebar").remove();
What I did was to put an echo at the end of my php with the variabel that is put in true or false, the I did this function inside the success option it is like this:
success: function(response){
if(response){
alert( "Success!");
}else{
alert( "Failed!" );
}
}
This worked for me, and you can put this in the php
if($myvar){
$anothervar=1;
}else{
$anothervar=0;
}
echo $anothervar;
so you can do this:
success: function(response){
if(response==1){
alert( "Success!");
}else{
alert( "Failed!" );
}
}
this is the way that I do it and it works fine
Hope it is useful
No. The success and error options relate to the success or failure of the XHR request. You need your php script to output something and check that. For example if your php script outputs "ok" (i.e. echo("ok");) if the verification is successful, you would use an ajax request such as this one
$.ajax({
url: 'sql/login.php',
success: function(data) {
if(data=="ok") {
alert('Login successfull.');
} else {
alert('Login failed.');
}
}
});
In your login.php:
if($_POST['data']){
$curData = $_GET['country'];
$query = "SELECT * FROM yourTable
WHERE tblData = '$curData'";
$result = mysql_query($query) or die;
if($result>0)
echo "<p class='checkExistance'>Data Exists</p>";
else
echo "<p class='checkExistance'>Data doesnt Exist</p>";
}
In your javascript:
function isSuccess(){
if($('.checkExistance').text() === "Data Exists"){
success($('.checkExistance').text()); //alert success!
}else{
success($('.checkExistance').text());
}
}
Did not really check if that works, but you pretty much get the idea. On AJAX call, do this:
$.ajax({
//
..
success:isSuccess
});
or
success:function(){
if($('.checkExistance').text() === "Data Exists"){
success($('.checkExistance').text()); //alert success!
}else{
success($('.checkExistance').text());
}
}
Make sure you implement alert() within the success() function..Hope that helps.
According to your information I assumed that your php page will do a validation and you make them return true or false within the php script
There are 2 problems in your code
1.your php page will return true or false within itself,in the other hand they won't send the result to ajax result unless you send them out like Tomm's said above
2.success() and error() of $.ajax are determined by the success of request NOT BY RESULT which mean that even if your php echo "false" it will trigger success() event because THE REQUEST IS SUCCESSFULLY SENT.