How can i put ajax in confirm button? - javascript

Hi friends i am trying to put ajax url in confirm button to update something in Database.
So i do this in JavaScript Section
function freeze_account() {
$.confirm({
title: 'Confirm!',
content: 'This dialog will automatically trigger \'cancel\' in 6 seconds if you don\'t respond.',
type: 'red',
typeAnimated: true,
boxWidth: '30%',
useBootstrap: false,
buttons: {
confirm: function() {
var manager_id = $('#manager_id').val();
$.ajax({
url: "update_freeze.php",
type: "POST",
data: {
'manager_id': manager_id
},
success: function() {
location.reload();
}
});
},
cancel: function() {}
}
});
}
and this is code for update
$manager_id = $_POST['manager_id'];
$state = '0';
$update=runQuery("UPDATE `users` SET `userStatus` =:userS WHERE `userID`=:user_id");
$update->bindparam(":userS",$state);
$update->bindparam(":user_id",$manager_id);
$update->execute();
My problem is when i press confirm button ajax works and go to another page but nothing happen in database.
What is wrong in my code Or Maybe I miss something?
any help any idea i will be grateful
Best Regards

look how i solved my problem
Maybe one benefit of my code
Thanks for every one suggestions or helping me
function freeze_account() {
var pid = $('#manager_id').val();
bootbox.dialog({
message: "Are you sure you want to Freeze this account ?",
title: "<i class='glyphicon glyphicon-trash'></i> Freeze !",
buttons: {
success: {
label: "No",
className: "btn-success",
callback: function() {
$('.bootbox').modal('hide');
}
},
danger: {
label: "Freeze!",
className: "btn-danger",
callback: function() {
$.post('update_freeze.php', { 'pid':pid })
.done(function(response){
bootbox.alert(response);
location.reload();
})
.fail(function(){
bootbox.alert('Something Went Wrog ....');
})
}
}
}
});
}

You need to set up an event listener on your button. Firstly, ensure you have an ID on your button so we can grab it.
Now, we create the event listener:
$("#button").on("click", freeze_account());
And, now when you click the button the ajax call should go through successfully.
However, it will still redirect yo due to its default behaviour.
To override this, simply prevent the default event:
function freeze_account(event) {
event.preventDefault(); // stops the button redirecting
$.confirm({
title: 'Confirm!',
content: 'This dialog will automatically trigger \'cancel\' in 6 seconds if you don\'t respond.',
type: 'red',
typeAnimated: true,
boxWidth: '30%',
useBootstrap: false,
buttons: {
confirm: function() {
var manager_id = $('#manager_id').val();
$.ajax({
url: "update_freeze.php",
type: "POST",
data: {
'manager_id': manager_id
},
success: function() {
location.reload();
}
});
},
cancel: function() {}
}
});
}

Related

Triggering event on clicking OK button in Jquery Modal dialog box

I am trying to display a dialog box with just an OK button on response of an ajax call. When the user clicks OK, it should reload the page. But now page reload is immediately happening after the dialog box is popped up. It is not waiting for the user to click OK. FYI I am using Jquery Modal dialog box.
Simple browser alert() does the job for me, but I don't like the appearance of alert().
Any help is highly appreciated!
$.ajax({
url: "modules/mymod/save.php",
type: "POST",
data: $('#requestForm').serialize(),
statusCode: {404: function () {alert('page not found');}},
success: function (data) {
// alert(data);
modal({type: 'alert', title: 'Alert', text: data});
window.location.href = window.location.href;
}
});
Reference:
$.ajax({
url: "modules/mymod/save.php",
type: "POST",
data: $('#requestForm').serialize(),
statusCode: {404: function () {alert('page not found');}},
success: function (data) {
// alert(data);
modal({
type: 'alert',
title: 'Alert',
text: data,
buttons: [{
text: 'OK', //Button Text
val: 'ok', //Button Value
eKey: true, //Enter Keypress
addClass: 'btn-light-blue btn-square', //Button Classes
onClick: function() {
window.location.href = window.location.href;
}
}, ],
center: true, //Center Modal Box?
autoclose: false, //Auto Close Modal Box?
callback: null, //Callback Function after close Modal (ex: function(result){alert(result);})
onShow: function(r) {
console.log(r);
}, //After show Modal function
closeClick: true, //Close Modal on click near the box
closable: true, //If Modal is closable
theme: 'xenon', //Modal Custom Theme
animate: true, //Slide animation
background: 'rgba(0,0,0,0.35)', //Background Color, it can be null
zIndex: 1050, //z-index
buttonText: {
ok: 'OK',
yes: 'Yes',
cancel: 'Cancel'
},
template: '<div class="modal-box"><div class="modal-inner"><div class="modal-title"><a class="modal-close-btn"></a></div><div class="modal-text"></div><div class="modal-buttons"></div></div></div>',
_classes: {
box: '.modal-box',
boxInner: ".modal-inner",
title: '.modal-title',
content: '.modal-text',
buttons: '.modal-buttons',
closebtn: '.modal-close-btn'
}
});
}
});
Because your reload runs irrespectively of what is clicked. If you want to assign a callback function to the modal window:
jQuery UI dialog with boolean return - true or false
Also, there is no need to make location.href equal itself (or use the window object). location.reload() works just as well.
You can pass the dialog modal buttons attributes, each with a registered event, like this:
$.ajax({
url: "modules/mymod/save.php",
type: "POST",
data: $('#requestForm').serialize(),
statusCode: {404: function () {alert('page not found');}},
success: function (data) {
$("#dialog-confirm").dialog({
resizable: false,
height: 200,
modal: true,
buttons: {
Proceed: function() {
window.location.href = window.location.href;
},
Cancel: function() {
// Cancellation code here
}
}
});
}
});
Simple browser alert() does the job for me because alert() is an blocking call. If you omit the alert then your code is not bind with any event to check whether user clicked on a button or not, that's why the code block executes immediately and page reloads.
So bind the following code:
window.location.href = window.location.href;
inside some button click, to resolve the issue.
dont use window.location function in success.instead open the modal with ok button at success(how to do that, I think you know already) and assign some id to that button let say id="loction_btn".
then use just this
$('document').on('click','#location_btn',function(){
window.location.href = window.location.href;
});

jQuery PHP Ajax Check User Logged in show modal

I have jQuery PHP Ajax to check user logged in or not.
JS
jQuery(document).ready(function()
{
setInterval(function()
{
jQuery.ajax({
url: 'chkLoggedin.php',
type: 'POST',
success:function(response)
{
if(response == "sessionExpired")
{
bootbox.dialog(
{
message: "Please login to continue",
title: "Not logged in",
buttons:
{
success:
{
label: "Log in",
className: "btn-success",
callback: function()
{
$('.bootbox').modal('hide');
}
}
}
});
return false;
}
}
});
}, 5000);
});
PHP
require("config/db.php");
session_start();
include("config/session.php");
if(empty($session))
{
echo "sessionExpired";
}
I tried the above code is working, but after logout the modal show multipe until I refresh the page. I just want the modal show 1 time.
Use setTimeOut function instead of setInterval

Can someone look at my Bootstrap Switch onSwitchChange. It does not work

Not sure what i am doing wrong here other than i am very weak in JQuery. The code in my onSwitchChange is not working. If i were to change it and put in alert("something"), it fires the alert, so i assume its in the ajax request. I have a breakpoint on my controller, but it never even hits the controller.
$(document).ready(function () {
$("[name='my-checkbox']" ).bootstrapSwitch({
onText: "Yes",
offText: "No",
onColor: "success",
offColor: "danger",
animate: false,
onSwitchChange: function (event, state) {
$ajax({
url: '/ProposalWork/ChangeActivityStatus/',
data: { id: #ViewBag.Activity.id, state: state }
}).done(function () { alert('Status Changed'); });
}
});
});
You missed a . in your ajax call.
$.ajax({
})

jQuery fileDownload conflicting with another jQuery plugin

I have two different jquery plugins loaded, one is UI related which allows me to display message popups and the other is the ajax fileDownload plugin. They both work fine. However, when I seem to run one function, it then starts conflicting with the other function.
I have a function called Export which initiates the fileDownload ajax request when a button is clicked. But then after the fileDownload is over, if I click on the button that launches the ExitAlert function, I end up getting the fileDownload re-initialising with the exit message. Below are the two functions.
Any idea what is going wrong?
Thanks
function Export() {
$("#Form").submit(function (e) {
e.preventDefault();
$.fileDownload('export.php?'+ Math.random(), {
httpMethod: 'POST',
dataType: 'text',
contentType: 'application/x-www-form-urlencoded',
data: $('#Form').serialize(),
successCallback: function (url) {
$("#ExportButton").prop("disabled", true);
$(pleaseWait).remove();
},
failCallback: function (responseHtml, url) {
$(pleaseWait).remove();
}
});
});
}
function ExitAlert() {
$("#Form").submit(function (e) {
e.preventDefault();
$.msgBox({
title: "Are You Sure?",
content: "<font size=2><b>Exit without saving? </b><br><br>All changes will be lost!</font>",
opacity:0.8,
type: "confirm",
buttons: [{ value: "Yes" }, { value: "No" }],
success: function (result) {
if (result == "Yes") {
document.Form.submit();
}
}
});
});
}
I seemed to have got it to work by changing the e.preventDefault and the functions now look like this (seems to work now):
function Export() {
$("form").submit(function (e) {
e.preventDefault();
});
$.fileDownload('export.php?'+ Math.random(), {
httpMethod: 'POST',
dataType: 'text',
contentType: 'application/x-www-form-urlencoded',
data: $('#Form').serialize(),
successCallback: function (url) {
$("#ExportButton").prop("disabled", true);
$(pleaseWait).remove();
},
failCallback: function (responseHtml, url) {
$(pleaseWait).remove();
}
});
}
function ExitAlert() {
$("form").submit(function (e) {
e.preventDefault();
});
$.msgBox({
title: "Are You Sure?",
content: "<font size=2><b>Exit without saving? </b><br><br>All changes will be lost!</font>",
opacity:0.8,
type: "confirm",
buttons: [{ value: "Yes" }, { value: "No" }],
success: function (result) {
if (result == "Yes") {
document.Form.submit();
}
}
});
}

Why is my ExtJS form not submitting?

I'm using ExtJS to pop up a window with a simple edit form, but on pressing the submit button, no XHR call is made and I get a this.form.el.dom is undefined error reported in the console.
Here's my code:
var myNameSpace = new function(){
var editForm, editWindow;
this.init = function(){
Ext.Ajax.request({
url: '/server/action.php',
success: function(result){
console.log('ajax is working ok'); // I get this
}
});
editForm = new Ext.form.FormPanel({
width:450,
autoHeight: true,
header : false,
items: [{
name: 'color',
fieldLabel: 'Color',
xtype: 'textfield',
value: 'blue'
}],
buttons: [{
text:"Submit",
scope: this, // tried without this, too
handler: function(){
// editForm.getForm().getValues() returns normal values
editForm.getForm().submit({
url: '/server/action.php',
success: function(form, action) {
console.log('Yes! Success!'); // I don't get this
},
failure: function(form, action) {
console.log('failed.'); // I don't get this
}
});
editWindow.close(); // works
console.log('the form is now closed'); // I get this
}
}]
});
editWindow = new Ext.Window(
{
title:'Enter your color',
autoWidth: true,
autoHeight: true,
layout: 'fit',
modal: true,
items: editForm,
closeAction: 'hide'
});
editWindow.show();
};
};
Ext.onReady(function () {
myNameSpace.init();
});
Any light on the subject will be greatly appreciated and profusely upvoted.
I am going to say that the issue is asynchonous nature of form submital. You form closes before the response is received from the Ajax submit event. Try moving your editWindow.close() line inside the success processing block.

Categories

Resources