POST request on Ajax Complete - javascript

I am trying to do a token exchange after every AJAX request performed on my site.
To do this, I am currently using the jQuery function .ajaxSuccess.
My problem is, whenever I try to perform an AJAX request within this function, it's obviously seeing it as a success and is this creating a recurring function.
How can I make a one-time AJAX request situated within this function which only runs once?
I.e. like so:-
$(document).ajaxSuccess(function() {
$.post("somewhere", {some: "data"}, function(data){
console.log(data);
});
});

You can check, if you actually need to make an AJAX request in your ajaxSuccess handler like so
$(document).ajaxSuccess(function(event, xhr, settings) {
if (settings.url != "somewhere") {
$.post("somewhere", {some: "data"}, function(data){
console.log(data);
});
}
});

Related

jquery ajax isn't working on the correct order

I am trying to load from a PHP file using ajax, some JSON objects but my problem is that my javascriptcode is not working on the correct order. Here is my code:
var requests;
$(document).ready(function(){
setInterval(function(){
$.ajax({
url: "test2.php",
success: function(result){
requests = JSON.parse(result);
alert(requests);
}
});
})
});
alert(requests);
Here is the first alert i'm getting on page load and here is the second alert
My question is why the alert in the last line is executed before the ajax
Note: this is a small example of my project, my real error is that i cannot load some arrays i need using ajax, because it shows as undefined at console, even if the ajax is in the beginning of the script.
try this cod for ajax call with php
$.ajax({
type: "method", // post or get
url: "file url",
dataType: "json",
success: function(data){
},
error: function(){
}
});
The best way to avoid this is to create a function in which second alert would be placed. And call this function inside ajax call's success method.
e.g.
ajax({
...
success: function(){
...
secondAlert();
};
...
});
function secondAlert(){
alert("alert after jax call");
};
As for
My question is why the alert in the last line is executed before the ajax
AJAX is an acronym for Asynchronous JavaScript and XML. The keyword here is asynchronous. AJAX sends the HTTP request and keeps executing the code in async fashion. The callback function of the AJAX request is executed after the request is finished and the corresponding response has been received. More info is available here

performing two success handlers on Ajax requests

I'm building a web application which has a lot of ajax requests scattered around all templates
I'm using ajaxSetup on main template, from which all other templates will inherit. In this ajax setup I do some pre and post processing.
//on main.html
$.ajaxSetup({
beforeSend: function (xhr)
{
//stuff
},
success: function (data)
{
//other stuff
}
})
Each ajax request, has a success handler of it's own, which must also be performed.
The problem is, that the success handler of the ajax requests will overide the global one defined in ajaxSetup.
//on specific.html
$.ajax({
success: function (data){
//request specific request handler which overrides $.ajaxSetup.
}
})
My question is, is there anyway I can work around this replacement? I didn't want to have to write the same code, or function call on each of the individual ajax requests.
thanks in advance
You could use ajaxSuccess to accomplish this http://api.jquery.com/ajaxSuccess/:
$( document ).ready(function(){
$(this).ajaxSuccess(function( event, request, settings ) {
console.log("Global Success")
});
$.ajax({method: "GET", url: "/echo/json",success : function(e){
console.log("Success");
}});
});
http://jsfiddle.net/Jpv5P/1/

How do I intercept data after ajax call, converse to jquery.ajaxPreFilter

I would like to intercept and modify data from the server before the ajax success callback is executed
I have this code:
jquery.ajaxPrefilter(function (options, originalOptions, jqXHR) {
// Modify options, control originalOptions, store jqXHR, etc
});
and would like the equivalent:
jquery.ajaxPostfilter(function (dataComingFromServer) {
dataComingFromServer.applyMyModifications();
});
ajaxPostfilter does not exist though - is there another way of intercepting the response from the server before it reaches event handler:
This question is related to this one - but it was not answered:
How can I intercept ajax responses in jQuery before the event handler?
If you want to use a standardised function to modify your data before the specific callback, you can use a pattern like this:
// Boilerplate to modify your data
function preprocess(data){
data.foo = "bar";
return data;
}
// Your specific handlers
function logdata(data){
console.log(data);
}
function writedata(data){
document.write(data);
}
// AJAX requests
$('#foo').load('url1', function(data) {
logdata(preprocess(data));
});
$('#bar').load('url2', function(data) {
writedata(preprocess(data));
});
Of course, this can be baked into a method that wraps the traditional .ajax, making it more convenient to use.
Note that the dataFilter option pointed out by KevinB serves a similar purpose, but it is limited to the .ajax method. If you wanted to set a global filter for AJAX requests, you would use:
$.ajaxSetup({
dataFilter: preprocess
});
If you want to handle the data coming back from the server before the event handler, use datafilter:
jquery.ajaxSetup({
dataFilter: function (data, type) {
//modify the data
return data;
}
});

JQuery Callback Never Called

I have the following JS/JQuery snippet:
function add_item() {
var item = $("input:text[name='new_item']").val();
$.post("{{ url_for('add_item') }}",
{'item' : item},
function(data) {
alert(':}');
});
}
It performs a simple AJAX request to a Flask webserver and displays an alert box on success (the data always returns a JSON snippet). The AJAX request adds a field to a SQLite database and returns. On my dev box, this request completes very quickly using asynchronous requests. However, on another server this request takes a few seconds (less than the default timeout, though) using asynchronous requests.
Problem: When the request takes a long time to complete using asynchronous requests, the callback is never called. When I change the AJAX settings to be synchronous, the callback is always called.
Thank!
I would try the $.ajax() function over the post one. Seems to have been more maintained - 1.6.2 also seems to have some issues, so try 1.6.1 if you need to: http://api.jquery.com/jQuery.ajax/
Use the error method to find out what error you're getting.
function add_item() {
var item = $("input:text[name='new_item']").val();
$.post("{{ url_for('add_item') }}",
{'item' : item},
function(data) {
alert(':}');
}).error(function(jqXHR, textStatus, errorThrown) { alert("error"); });
}

Jquery ajax onSuccess event

I am doing AJAX with JQuery but every time the "onSuccess" event must be executed after another AJAX request disconnected.
Here is the code:
d.ajax({
url: f.options.url.offline,
dataType: "jsonp",
jsonp: "callback",
cache: false,
data: {
status: "offline",
ticket: f.connection.options.ticket
},
success: function(g) {
f._offlineSuccess()
},
error: function() {
f._offlineError()
}
})
All my AJAX requests are JSONP, and when the above code is triggered, there is another AJAX connection (long polling request, last about 10 senconds) already established in the mean time. So the "f._offlineSuccess" function is always executed after another AJAX connection disconnected.
I can not see any relationship between the two AJAX requests, and I don't know why the "onSuccess" function must be executed after another AJAX connection stopped.
Any help is appreciated~
================================
updated:
I just found out if I have two JSONP connection at the same time, the "onSuccess/onFailure" function will be blocked. I don't know if some one encountered the same problem before?
Ajax requests are asynchronous. so a new request is not going for the previous one to finish. If you want that behaviour use async parameter to false, or use the complete() function to call for another request. This will fire only when the first request is finished.
UPDATE
For JsonP use jQuery.getJSON() and do the second request on callback if the call was succesfull.
function (data, textStatus) {
// data will be a jsonObj
// textStatus will be one of the following values:
// "timeout","error","notmodified","success","parsererror"
this; // the options for this ajax request
}
If you use firebug - net tab, you will be able to see the full url of the two jsonp requests. You should be able to see the callback function names on the end of the url. Are these different or the same? I can only assume they are the same.

Categories

Resources