Can ajaxSetup.success callback prevent ajax.complete callback from being called? - javascript

In $.ajaxSetup.success I want a general piece of code to check something and then the $.ajax.complete callback should not be called. Is this possible? Preferably by doing something in the $.ajaxSetup.success callback and not in every $.ajax.complete callback.
event.stopImmediatePropagation might work, but I don't know how to access event from success.
$.ajaxSetup({
success : function(jqXHR, textStatus, errorThrown) {
alert('this will happen');
}
});
$.ajax({
url: '/echo/json/',
type: 'POST',
complete: function () {
alert('this shouldn\'t happen');
}
});
jsFiddle: http://jsfiddle.net/z4L4z3oo/1/

Related

Success is always fired even when the response is an error

I have an Ajax function that takes in 4 parameters. The url, the data, the success callback and error callback functions. I'm trying to make this Ajax function as reusable as possible. Here's how it looks:
function send_data(url, data, successCallback, errorCallback) {
$.ajax({
url: url,
type: 'post',
data: data,
success: successCallback,
error: errorCallback
});
}
Where the success callback looks like this:
function createMessage(message) {
console.log(message);
}
and error callback looks like this:
function createErrorMessage(message) {
console.log(message);
}
However, when I call the Ajax function with parameters that should return a 400 error bad request, the success function is always fired regardless if it is a 200 or 400 response. I don't understand why the success callback function is firing when only the error function should be firing. However, both are firing. Why is this?
The problem is in these lines
success: successCallback,
error: errorCallback
They both are running immediately one after the other so both are returning their values.
Make an anonymous callback function on both success and error and it will work fine.
success: function() {
successCallback();
},
error: function() {
errorCallback();
}

Waiting for ajax Request using Callbacks

I was trying to use callbacks to wait for Ajax request but it wouldnt work
.can someone please tell me the logic behind callbacks and help me in-cooperate it in my laravel code.
function sendImageToController(callback){
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name="csrf-token"]').attr('content') }
});
$.ajax({
url: "{{route('HeatMap.moveToStorage')}}",
data: {"imgUrl":imgUrl,
"targetHeatMap":myMap
},
type:'post',
success:function(response){
//Refresh After Creating the image
if(!window.location.hash) {
// alert('Please Wait Loading');
//window.location = window.location + '#loaded';
//window.location.reload();
}
console.log("correct");
console.log(response);
},
error:function(e){
console.log(e);
},
});
}
you need to call callback function from success and error function
success:function(response){
callback(null, response);
}error:function(e){
callback(e, null);
}
so it will call callback function in callback function first argument will be error and second will be result.

Ajax - All request are Done/Completed

I have a difficulty to know when all Ajax requests are completed because I need this information to call another function.
Difficulty are to know when my 4/5 function with requests are completed. I use native function of ajax and none is working for me.
I used Chrome, and async requests.
Someone Helps me
I use this(not work):
$(document).ajaxStop(function() {
alert("Completed");
});
and this (not Work):
$(document).ajaxComplete(function() { alert("Completed"); });
Both ways I try use in another function thal calls all requests:
Example:
function Init()
{ Search("123"); Search2("1234"); Search3("12345");
... }
Extract one (of 5 requests,others are very similar ) of my request:
function Search(user) {
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
success: function(response, textStatus, jqXHR) {
try {
if (response != null) {
alert("Have Data");
} else {
alert("are empty");
}
} catch (err) {
alert("error");
}
},
error: function() {
alert("error");
}
}); }
have you tried putting it in a done function? something like...
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP'
}).done(function (data) {
code to execute when request is finished;
}).fail(function () {
code to do in event of failure
});
bouncing off what Michael Seltenreich said, his solution, if i understand where you guys are going with this...might look something like:
var count = 0;
function checkCount(){
if(count == 5 ){
//do this, or fire some other function
}
}
#request one
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
#request two
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
and do it with your five requests. If that works out for you please make sure to mark his question as the answer;)
You can create a custom trigger
$(document).trigger('ajaxDone')
and call it when ever you finished your ajax requests.
Then you can listen for it
$(document).on('ajaxDone', function () {
//Do something
})
If you want to keep track of multiple ajax calls you can set a function that counts how many "done" values were passed to it, and once all are finished, you can fire the event.
Place the call for this function in each of the 'success' and 'error' events of the ajax calls.
Update:
You can create a function like so
var completedRequests= 0
function countAjax() {
completedRequests+=1
if(completedRequests==whatEverNumberOfRequestsYouNeed) {
$(document).trigger('ajaxDone');
}
}
Call this function on every success and error events.
Then, ajaxDone event will be triggered only after a certain number of requests.
If you wanna track specific ajax requests you can add a variable to countAjax that checks which ajax completed.

jQuery invoke function only when ajax of the previous function was executed

I have the following problem:
$('#id').on('click', '.class', function(){
// it is doing something and
// executing AJAX request
// with the data from request it is doing something
} // this is onclick handler
Later in the code I need to execute it as well and after executing I need to run another function which depends on the ajax execution of this onclick handler, so I am doing something like this
$('#id .class').click();
anotherFunction();
It is not working. The problem is understandable, because the ajax request has not finished.
I tried to achieve the right execution using the idea of Deferred object.
$.when( $('#id .class').click() ).then( anotherFunction() );
And using the idea of autoexecuted functions with callback:
(function(o, callback){
$('#id .class').click()
})(null, anotherFunction() );
Both ideas failed.
Is there any way to achieve the intended functionality without modifying anotherFunction() and onclick function?
Not sure if I entirely understand your question, but what keeps you from executing your onsuccess / onerror code in the corresponding $.ajax response methods?
$.ajax({
type: 'POST',
url: "your url",
data: "your data",
error: function(jqXHR, textStatus, errorThrown) { ... },
success: function (data, textStatus, jqXHR) { ... }
});
Also, why don't you put the ajax executing part to an own function and call it from the event handler and on every other place, like this?
function ajaxMe(onerror, onsuccess)
{
$.ajax({
type: 'POST',
url: "your url",
data: "your data",
error: function(jqXHR, textStatus, errorThrown) { onerror(...) },
success: function (data, textStatus, jqXHR) { onsuccess(...) }
});
}

jQuery: How do you perform a callback inside an AJAX call

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.

Categories

Resources