javascript ajax call before send is not executed - javascript

I have this Javascript code:
this.confirmBox = function(data) {
$.jconfirm((function(_this) {
return function() {
var objConfig;
objConfig = $.jconfirm("getConfig");
alert("here");
return true;
};
})(this));
return false;
};
this.beforeSend = function(event, jqXHR) {
if (this.confirmBox()) {
return this.disableSubmit();
} else {
return jqXHR.abort();
}
};
When I run the script I am landing on alert("here") and return true for the function confirmBox.
The problem however is that the ajax call itself is not triggered anymore for some reason. How do I need to adjust the beforeSend function in order to check if the checkBox result is true or false?

You have to add the event on the buttons
Please see this fiddle example
buttons: {
"Yes": function () {
$(this).dialog('close');
callback(true);
},
"No": function () {
$(this).dialog('close');
callback(false);
}
}

I think call to confirmBox method in beforeSend always returns false because $.msgbox does not block thread execution like window.confirm method does. Probably you need to invoke ajax call when you get the result === "Confirm" from message box.
$.msgbox("confirm", {
type: "confirm",
buttons: [
{ type: "cancel", value: "Cancel" },
{ type: "submit", value: "Confirm" }
]}, function(result) {
if (result === "Confirm") {
// $.ajax(..)
}
}
};

Related

$.deferred does not work as expected

on some button's click event I'm calling function a() which contains below mentioned Ajax call, in the success I'm using $.Deferred. It works perfectly fine on very first click of the button but when I click a button second, third, fourth... or nth time it does not work as expected (It does not go inside of confirmation function at all). what I'm doing wrong. Thank you in advance.
$.ajax({
type: "GET",
url: "some url",
data: {
parameters
},
success: function (result) {
//result is an Array object. for example **result:Array[3]**, further expand result will be like this **result[0]:Array[19], result[1]:Array[39], result[2]:Array[15]**
var defer = $.Deferred();
function confirmation(result) {
if (result.length > 1) {
$('#field' + questionID).append('<div id=dialog></div>');
$("#dialog").append('<div id=grid></div>');
$("#dialog").kendoDialog({
modal: true,
visible: false,
draggable: true,
closable: false,
title: "Please Select One Submission",
maxWidth: 500,
//maxHeight:300,
animation: {
open: {
effects: "slideIn:down fadeIn",
duration: 500
},
close: {
effects: "slide:up fadeOut",
duration: 500
}
},
actions: [
{ text: 'OK', primary: true, action: onOK }
]
});
$("#grid").kendoGrid({
dataSource: {
data: result,
schema: {
data: function (result) {
return $.map(result, function (item) {
return $.map(item, function (innerData) {
for (var i = 0; i < displayFields.length; i++) {
if (displayFields[i] == innerData.FieldIDString) {
return {
EntryGroupID: innerData.EntryGroupID,
FieldTextString: innerData.FieldTextString,
EntryValue: innerData.EntryValue
}
}
}
});
});
}
},
pageSize: 2,
group: { field: "EntryGroupID" }
},
filterable: {
mode: "row"
},
pageable: {
refresh: true,
},
noRecords: {
template: "No records to display"
},
groupable:false,
//scrollable: true,
selectable: true,
columns: [{
field: "EntryGroupID",
title: "Submissions",
filterable: {
cell: {
operator: "contains"
}
}
}, {
field: "FieldTextString",
title: "Questions",
filterable: {
cell: {
operator: "contains"
}
}
}, {
field: "EntryValue",
title: "Answers",
filterable: {
cell: {
operator: "contains"
}
}
}]
});
var wnd = $("#dialog").data("kendoDialog");
wnd.wrapper.find('.k-dialog-title').css('background', CIMSFields.backgroundColour).css('color', CIMSFields.textColour).css('width','100%').css('text-align','center');
wnd.open().center(true);
//in this function i'm waiting for user response which they will choose one array object based on this value **Confirmation** function will get the data.
function onOK(e) {
var data = [];
var grid = $("#grid").data("kendoGrid");
var selectedItem = grid.dataItem(grid.select());
if (selectedItem != null) {
$.map(result, function (item) {
if (selectedItem.EntryGroupID == item[0].EntryGroupID) {
data.push(item);
defer.resolve(data);
}
});
}
else {
defer.resolve(data);
}
wnd.close();
}
}
else
{
defer.resolve(result);
}
return defer.promise();
}
alert(defer.state());
confirmation(result).then(function (data) {
//it never reach here except first time
alert(defer.state());
alert(data);// data is the user selected value from the grid.
})
}
});
If result is an array, .empty is not an Array property or method. $.Deferred() is not necessary, $.ajax() returns a jQuery promise object.
You can check .length of expected array, or property of expected object at .then() chained to a() call. Also, chain .fail() to log and handle errors that could possibly occur.
function a(/* parameters */) {
// note, we are `return` ing `jQuery.ajax()` call,
// which returns a jQuery promise object
return $.ajax({type: "GET", url: "some url", data: {parameters}})
}
a()
.then(function(result, textStatus, jqxhr) {
console.log(result.length, jqxhr.state());
if (result.hasOwnProperty("empty")) { console.log(result.empty); }
else { console.log("result does not have property \"empty\""); };
})
// log, handle errors here
.fail(function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown, jqxhr.state());
});
found my answer here
basically my need was I have to wait for user response in the function before proceeding further. Thank you all who took time to respond my question. I appreciate your time and effort. Most importantly I'm not using deferred at all now.

Jquery close popup on click

I use this jquery to show my popup,
//ResetPassword Popup display
$(document).ready(function () {
var passwordExpiredVal = $("#isPasswordExpired").html();
if (passwordExpiredVal == "True") {
$("#ResetPasswordModal").modal({
show: 'true'
});
};
});
I use this jquery to pass the new typed password to controller action ON CLICK, once the save button is clicked I want the popup to close
//Reset Password submit
$(document).ready(function () {
$("#submitSave").on("click", function () {
var confirmPassword = $("#txtLgnPasswordConfirmReset").val();
var passwordReset = {
UserName: $("#txtLgnUsername").val(),
Password: $("#hdnOldPassword").val(),
NewPassword: $("#txtLgnPasswordReset").val()
}
if (passwordReset.NewPassword != confirmPassword) {
notifyMessage.showNotifyMessage('error', 'The passwords entered should match', false);
$("#txtLgnPasswordReset").val("");
$("#txtLgnPasswordConfirmReset").val("");
}
else {
$.ajax({
type: "POST",
url: "/Account/PasswordReset",
data: passwordReset,
success: function () {
$("#ResetPasswordModal").modal({
show: 'false'
});
},
error: function () {
alert('failure');
}
});
}
});
});
My jquery function is not helping...
success: function () {
$("#ResetPasswordModal").modal({
show: 'false'
});
},
Any ideas??
Thanks in advance...
The code you are using is unnecessarily initializing the modal again on that element.
Use modal('hide') : Docs,
success: function () {
$('#ResetPasswordModal').modal('hide');
},
If you further wish to use this again, 'toggle' would be a better option.
$('#ResetPasswordModal').modal('toggle')

How to override the jQuery.ajax success function after it has been initialized?

A button click triggers an ajax request. When the user clicks the button a second time while the first request is still loading, i want to override the first request's success function with another one.
Basically I want to do this:
var ajaxRequest = null;
jQuery('#mybutton').click(function () {
if (ajaxRequest) {
ajaxRequest.success = function () {
};
}
ajaxRequest = jQuery.ajax({
url: '...',
success: function () {
console.debug('do something');
}
});
});
But the initial success handler is been called.
How to achieve an override?
You can try the following hack, I have tested it with asynch setTimeout (instead of asynch jQuery.ajax) and it works -
var mySuccessHander = function() {
console.debug('Initial function');
}
var test = jQuery.ajax({
url: '...',
success: function() {
mySuccessHander();
}
});
And when the button is clicked for the second time, execute following -
mySuccessHander = function() {
console.debug('Overridden function');
}
Nice question , this will work..
var isRequestDone = true;
jQuery('#mybutton').click(function () {
var requestParams = {
url: '....',
beforeSend: function () {
isRequestDone = false;
},
success: function () {
isRequestDone = true;
console.debug('do something');
},
error: function () {
isRequestDone = true;
}
}
if (!isRequestDone) {
requestParams.success = function () {
console.log('please wait for a while!');
};
}
jQuery.ajax(requestParams);
});
beforeSend will fire just before the request will go to server , so when request in on the server isRequestDone will be false and hence will change success handler . on success callback from the first request it will again back to original.
You can set the ajax arguments to a variable first so you can modify it later on.
var clicks = 0,
ajaxArgs = {
url: '...',
success: function () {
console.debug('do something');
}
};
$('#myButton').click(function() {
++clicks;
if (clicks > 1) {
// set the success function if clicked more than once
ajaxArgs.success = function () {
console.debug('Success function ' + clicks);
}
}
$.ajax(ajaxArgs);
});
If you want to modify the success function only when ajax is still loading you can do this:
var loading = false,
ajaxArgs = {
url: '...',
success: function () {
console.debug('do something');
}, complete: function () {
loading = false;
}
};
$('#myButton').click(function() {
if (loading) {
// set the success function if ajax is still loading
ajaxArgs.success = function () {
console.debug('Another Success function ');
}
} else {
loading = true;
$.ajax(ajaxArgs);
}
});

Abort AJAX and form submitions, save them, change them, and send it later

I need to request additional credentials to a user when he clicks certain buttons and submits certain forms.
I way I am trying to do it is:
Intercept the submit event, abort it, and store a copy
Ask for the credentials with an prompt dialog (not the JS native one, so this is all non-blocking)
If user inputs the credentials, insert the fields into the event data and send it to the server.
My current code for AJAX requests is:
$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
if (ajaxOptions.type === "POST") {
$.current_request = jqXHR;
jqXHR.abort();
$.check_password_with_my_dialog();
}
});
$.check_password_with_my_dialog: function() {
$("#validate-password-prompt").dialog({
modal: true,
title: "input pw",
buttons: {
Ok: function() {
$.password = $("#validate-password-prompt input").val();
$.deliver_current_request();
return $(this).dialog("close");
},
Cancel: function() {
return $(this).dialog("close");
}
}
});
}
deliver_current_request: function() {
$.current_request.beforeSend = function(jqXHR, ajaxOptions) {
ajaxOptions.data = ajaxOptions.data.concat("&password=" + $.password);
};
$.ajax($.current_request);
}
The problem so far is that ajaxOptions.data is undefined, so I can't add my data.
And the requests seems to be going as a GET instead of POST.
Am I doing this the right way, or am I way of?
updated
Here is a way i can think of to accomplish answer for your question.
<form id="myForm" >
<button id="submit-form-btn">Submit</button>
</form>
<div id="validate-admin-password-prompt">
<input type="password"/>
</div>
In javascript,
function submitForm(pwd) {
var formData = $('form#myForm').serialize() + "&password=" + pwd;
$.ajax({
type: "POST",
url: "http://google.com",
data: formData,
dataType: "script"
});
alert("POSTed: " + formData.toString());
}
function alertDialog() {
$("#validate-admin-password-prompt").dialog({
modal: true,
title: "Admin password is required",
zIndex: 10000,
buttons: {
Ok: function() {
$(this).dialog("close");
var pwd = $("#validate-admin-password-prompt input").val();
submitForm(pwd);
},
Cancel: function() {
$(this).dialog("close");
alert('Not authorized to submit the form');
return false;
}
}
});
}
$("#submit-form-btn").click(function(e) {
e.preventDefault();
$ele = $("#validate-admin-password-prompt input");
if ($ele.val()==null || $ele.val().trim()=="") {
alertDialog();
} else {
submitForm($ele.val());
}
});

Returning jQuery Ajax Post

I wish to use the jQuery.post class to return (not alert) the response within a function.
The following gives an alert with the appropriate value:
function test_func() {
$.post("test.php", { cmd: "testing" }, function (data) { alert(data); })
}
(displays alert with appropriate value)
I tried the following:
function test_func() {
return $.post("test.php", { cmd: "testing" }, function (data) { return data; })
}
(returned object)
function test_func() {
var tmp;
$.post("test.php", { cmd: "testing" }, function (data) { tmp=data; })
return tmp;
}
(returned undefined)
var tmp;
function setTmp(n) {
tmp=n;
}
function test_func() {
t=$.post("test.php", { cmd: "testing" }, function (data) { setTmp(data); })
}
(returned undefined)
function test_func() {
t=$.post("test.php", { cmd: "testing" })
return t.responseText;
}
(returned undefined)
So what's the deal? How can I make "test_func()" return the data response text?
Being an asynchronous request, you aren't able to get a response as soon as you call the function. Instead, the function that you pass to $.post is intended to be a callback that will perform some action as soon as the response is complete. Consider the following:
function myCallback(response) {
// do something with `response`...
}
function test_func() {
$.post("test.php", { cmd: "testing" }, myCallback)
}
Instead of directly returning a response, you can instead manipulate it as needed in the myCallback function.
The deal is ajax is asynchronous one possible solution is to set it as sync like
$.ajaxSetup({
async:false
});
and then
function test_func() {
var temp;
t=$.post("test.php", { cmd: "testing" })
return t.responseText;
}
the answer is only to make your current setup work else there are better ways to deal with it

Categories