How to call beforeSend only in success? Right now, my button is also changing text to "Working" when error comes into ajax call.
success: function(data) {
alert("operation successful");
},
beforeSend: function() {
btnSubmit.val("Working...");
},
error: function(response) {
alert("something went wrong");
}
Use "complete" to alter the button text
complete: A function to be called when the request finishes (after success and error callbacks are executed)
success: function(data) {
alert("operation successful");
},
beforeSend: function() {
btnSubmit.val("Working...");
},
error: function(response) {
alert("something went wrong");
},
complete:function() {
btnSubmit.val("Done");
}
}
Related
I want to display ajax result message before page refresh, but something is wrong. My code is like this:
$.ajax({
cache: false,
type: "POST",
url: "#(Url.RouteUrl("DummyRequest"))",
success: function (data) {
if (data.Success) {
$('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
setInterval(function () {
location.reload();
}, 5000);
}
else {
$('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
/*setInterval(function () {
location.reload();
}, 5000);*/
}
},
error: function (xhr, ajaxOptions, thrownError) {
$('#dummy-notification').text("Something went wrong.").fadeIn("slow").delay(3000).fadeOut("slow");
}
});
My code is working just fine on else situation. When I tried, message appears, then after 5 secs page reloads itself. But when if situation is on, page reloads itself, however message doesn't show.
How can I solve this problem?
Its depends on response time of server.. so if response from server is late then not working correctly.. so you have to wait for AJAX response then you have to display popup and redirect. so use ajax option async: false in your ajax request. as mentioned below
$.ajax({
cache: false,
async: false,
type: "POST",
url: "#(Url.RouteUrl("DummyRequest"))",
success: function (data) {
if (data.Success) {
$('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
setInterval(function () {
location.reload();
}, 5000);
}
else {
$('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
/*setInterval(function () {
location.reload();
}, 5000);*/
}
},
error: function (xhr, ajaxOptions, thrownError) {
$('#dummy-notification').text("Something went wrong.").fadeIn("slow").delay(3000).fadeOut("slow");
}
});
Try something like this:
$('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow", function () {
setTimeout(function () {
location.reload();
}, 5000);
});
The difference is that the setTimeout() will not be called until after the fadeOut() is finished executing.
i am writing this code in my html page to hide one id in that page..alerts are also not working..method is not called
*<script>
alert("yo");
$(function checkUsertype(email_id)
{
alert("yup")
var usertype = $("#txtusertype").val();
$.ajax({
alert("hide")
url: 'rest/search/userType?email_id='+email_id,
type : "GET",
datatype : 'json',
cache : false,
success : function(data)
{
if(usertype=='webuser')
{
$("#themer").hide();
}
},
error : function(xhr, data, statusText,errorThrown)
{
}
});
})
alert("yo");
<script/>*
This is the problem.
$.ajax({
alert("hide")
You're trying to alert inside the ajax which is Syntax error. Try removing the alert inside ajax and it should work.
You can use alert in success, error callbacks as follow:
$(function checkUsertype(email_id) {
var usertype = $("#txtusertype").val();
$.ajax({
url: 'rest/search/userType?email_id=' + email_id,
type: "GET",
datatype: 'json',
cache: false,
success: function(data) {
alert('In Success'); // Use it here
console.log(data); // Log the response
if (usertype == 'webuser') {
$("#themer").hide();
}
},
error: function(xhr, data, statusText, errorThrown) {
alert('In Error'); // Use it here
console.log(errorThrown); // Log the error
}
});
});
I am trying to set a button text to 'Email sent' on success or 'Emailed failed' on failure. I am using ajax to call a method in MVC.
The call to to MVC works fine, but my code calls setButtonSuccess and setButtonFailed even before the json is ran?
Here is my code:
$('input[type=button]').click(function () {
bookingID = $(this).closest('tr').attr('id');
sendEmail(bookingID, this);
});
function sendEmail(id, thisContext) {
var data = JSON.stringify({ 'id': id });
/*******
This calls setButtonSuccess AND setButtonFailed which is wrong
I want to execute only setButtonSuccess OR setButtonFailed depending on whether successful or not
*******/
jsonPOST("~Booking/ResendEmail", data, setButtonSuccess(thisContext, "Email Sent"), setButtonFailed(thisContext, "Email Failed"),false);
};
function setButtonSuccess(thisContext, buttonValue) {
$(thisContext).val(buttonValue);
$(thisContext).addClass("btn btn-success");
};
function setButtonFailed(thisContext, buttonValue) {
$(thisContext).val(buttonValue);
$(thisContext).addClass("btn btn-warning");
};
function jsonPOST (pWebServiceFunction, pData, pOnCallbackSuccess, pOnCallbackFailed, async) {
$.ajax({
type: "POST",
url: url + pWebServiceFunction,
data: pData,
contentType: "application/raw; charset=utf-8", dataType: "json",
async:async,
processdata: true,
success: function (msg) {
if (msg.success === true) {
pOnCallbackSuccess(msg);
}
else {
pOnCallbackFailed(url + pWebServiceFunction);
}
},
error: function (xhr, ajaxOptions, thrownError) //When Service call fails
{
pOnCallbackFailed(url + pWebServiceFunction, pData, xhr.status, xhr.statusText, xhr.responseText);
}
});
};
Thanks
You're calling the functions immediately instead of passing a function that will call them later. It should be:
jsonPOST("~Booking/ResendEmail", data, function() {
setButtonSuccess(thisContext, "Email Sent");
}, function() {
setButtonFailed(thisContext, "Email Failed");
}, false);
I have a function with an AJAX call inside it, I need to be able to call the function and it return true if the AJAX request was successful and false if not.
I know the following doesn't work because the returns are out of scope to the exampleFunc()
function exampleFunc() {
$.ajax({
url: 'http://example.com/page',
success: function(data, textStatus, XMLHttpRequest){
return true;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
return false;
}
});
}
I Googled for a solution and believe I should be doing a callback but couldn't seems to achieve the desired outcome.
Edit: Te be more specific I require the function to return true or false because my use case currently has me doing :
if (exampleFunc()) {
// run this code
}
You can't return from something asynchronous. The callback function has to do what you want to do in a forwards direction.
Simply pass the function to your exampleFunc() and call it in your ajax success callback.
// you want this function to be run on ajax success.
function sayHello() {
alert('hello');
}
function exampleFunc(callback) {
$.ajax({
url: 'http://example.com/page',
success: function(data, textStatus, XMLHttpRequest){
if (callback && typeof callback == 'function') {
callback() // here, you call sayHello, which is passed as parameter
}
return true;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
return false;
}
});
}
exampleFun(sayHello); // start ajax
function exampleFunc() {
$.ajax({
url: 'http://example.com/page',
async: false,
success: function(data, textStatus, XMLHttpRequest){
return true;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
return false;
}
});
}
Notice async: false
$.ajax is an asynchronous call which will have a callback handler on success/error response. To work around, you need to pass a callback.
function exampleFunc(callback, errorCallback) {
$.ajax({
url: 'http://example.com/page',
success: callback,
error: errorCallback
});
}
USAGE
exampleFunc(function(data, textStatus, XMLHttpRequest) {
// do whatever you want, you have got a success response
//return true;
}, function (XMLHttpRequest, textStatus, errorThrown) {
// error occured, show some red error box
//return false;
});
This can only be done if you got a sync function like:
function exampleFunc() {
var success;
$.ajax({
async : false,
url: 'http://example.com/page',
success: function(data, textStatus, XMLHttpRequest){
success= true;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
success= false;
}
});
return success;
}
What you can do is pass a function to your function. Something like:
var hello = "Hello World";
exampleFunc(function(){
alert(hello); // Alerts Hello World on success
},
function(){
alert("FAILED"); // Alerts FAILED on error
});
And the function will look like:
function exampleFunc(success, error) {
$.ajax({
url: 'http://example.com/page',
success: success,
error: error
});
}
But you can't change the hello var inside the function and use it after the function call. Because the call's keep async.
I'm trying to catch Ajax timeout error with jQuery 1.4.2, but none of tutorial I found work. In Firebug, when timeout error fires. I see:
uncaught exception: [object Object].
Please help me handle Ajax timeout. Here's my JS code:
$.ajax({
type:"POST",
url:"/data/add/",
data:
{
"date":$("input#date").val();
},
dataType:"json",
timeout:2000,
success: function(response) {
},
error: function () {
alert('Server error');
}
});
I tested this out, and if you remove the ; from your $("input#date").val() statement, it should work.
$.ajax({
type:"POST",
url:"/data/add/",
data:
{
"date":$("input#date").val()
},
dataType:"json",
timeout:2000,
success: function(response) {
},
error: function () {
alert('Server error');
}
});
something went wrong again, and i got googled this f*****g bug http://dev.jquery.com/ticket/6173 ! here is the spike:
success: function(response, textStatus, xhr) {
if (!xhr.status) {
alert("ERROR!!!!");
}
else {
// elided
}