jquery ajax.abort(), how to resend again? - javascript

This is in a Drupal context but i believe its common for all ajax requests.
On a beforeSend callback im aborting the request depending on DOM conditions like:
Drupal.ajax.prototype.beforeSend = function (xmlhttprequest, options) {
if ($(this.element).hasClass('disabled')) {
xmlhttprequest.abort();
}
})
Why can't I reprocess this request afterwards?
I mean, when the link is clicked again the code doesn't even go through beforeSend()..

Try:
xmlhttprequest.open('GET', 'page.txt');
xmlhttprequest.send();
doing this will reinvoke interrupted request

Related

Trying to POST only after an AJAX request but the POST keeps firing

I am trying to post after each completed ajax request ..
jQuery(function($) {
jQuery(document).ajaxComplete(function() {
$.post('/wp-admin/admin-ajax.php', {data:'hello'}, function(response) {
console.log(response);
});
});
});
This just keeps firing and won't stop. If I do an alert it only fires twice since there are two requests but the POST for some reason just keeps firing.
from the docs:
Register a handler to be called when Ajax requests complete. This is
an AjaxEvent.
obviously an event is being fired once the post request is done putting you in an endless loop.
You can use some thing like
$.get(....).complete(function(){
$.post('/wp-admin/admin-ajax.php', {data:'hello'}, function(response) {
console.log(response);
});
})
In case you want it to happen when ever an ajax request takes place you will have to add the event listener to each request and remove it in each $.post

AJAX event for when the server receives the request - before processing it

I'm currently developing a class in PHP that makes cURL requests and returns the answer as JSON for it to be processed by jQuery on my page. So far — no problems.
(Note that the only way for me to load that content is by using my own server - I'm querying a website's API with my private API key)
The problem is that some pages are slow (because of their server), and that plus the request to my server with jQuery makes it long to load a page, which makes around 5 seconds (or more) with no feedback at all for the user.
What I was wondering if there's any jQuery event for $.ajax which is called when the request is sent to the server (meaning that the server also started loading the requested page), but before the actual request to my page ended.
I'm trying to achieve this:
*user click* (0)
Sending request... (1)
Request sent. Loading page... (2)
Page loaded. (2)
Event 0 would be just a click
Event 1 would be jQuery's $.ajax({ beforeSend: function(){} );
Event 2 is what I want. It'd be something like onSend, but sadly it doesn't exist
Event 3 would be jQuery's $.ajax({ complete: function(){ } });
As a side note: I'm using jQuery, but I have no problems in using plain JavaScript if needed.
Maybe something like this can perform what you want:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 2) {
alert("loading page");
}
}
XMLHttpRequest has this states:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
I don't know if this really works. I never had to use a differente state of 4.
The Ajax have the default events that can be handled with here on the reference: http://api.jquery.com/jquery.ajax/
But i'll do a sample to you see how it works.
The HTML code for a sample:
<input type=button id=yourButtonID name=yourButtonID>
-> (0) - The onClick event.
$("#yourButtonID").click(AjaxFunction());
-> (1), (2), (3) The AjaxFunction.
function AjaxFunction(){
$.ajax({
url: "http://www.stackoverflow.com"
}).beforeSend(function() {
//show the ajax image
}).done(function(data) {
alert(data);
}).fail(function() {
alert("sorry, it failed");
}).success(function() {
alert("Sucess!");
});
}
If you want to show to the user that the Request is happening, you just need to show to the user a ajax loading image on the beforeSend event, like that one:
Something like onSend is the beforeSend because it executes before sending, and while are you sending, why you would fire a event?
Basically, ajax is a useful tool to make XHR's (XMLHTTPRequest's) that have pre-made events that you can use before you send the request, when your request is done, and if it fails, and if it success.
Basically, you want two responses from server: the first as soon as it receives your request, and the second containing the payload from the other server.
Since a regular ajax HTTP request can only have one response, you could use web sockets instead.
This allows the server to 'push' data to the client.
see the links below:
https://developer.mozilla.org/en-US/docs/WebSockets
http://www.html5rocks.com/en/tutorials/eventsource/basics/

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"); });
}

Simple way to monitor result of request to detect session timeout?

I've got an Ajax app I would like to add sessions and logins to.
Currently the app uses jQuery get shorthand to send a request
that.ajaxRequest = $.get(query_string, function(data, textStatus, xhr) {
// do somthing with data
});
I have a system on the server that throws an error message if the session has expired.
On the client I know I can deal with this using the following:
that.ajaxRequest = $.get(query_string, function(data, textStatus, xhr) {
if (data == "E_TIMEOUT") {
// redirect to login
} else {
// do something
}
});
However I would prefer not to have to write the same timeout code for every $.get - there are a bunch of them throughout the app.
Is there a way to monitor the result of a request and take action if necessary, without rewriting all of my $.get statements?
Thanks,
You can use $.ajaxSetup() for this:
$.ajaxSetup({
complete: function (xhr) {
if (xhr.getResponseHeader('E_TIMEOUT') == "1") {
//redirect to login
}
}
});
This approach is slightly different, it uses response headers which you can get without parsing data an extra time every request (that is possible, though not documented and subject to break), which you would have to do otherwise, in a global situation.
On the server-side where you're sending E_TIMEOUT for the response, just change it to add a header as well, E_TIMEOUT=1 (or whatever header you want). I actually put this header on my login page only, the timeouts redirect via a 302 (which XmlHttpRequest transparently follows), so if the user timeouts and the AJAX request actually ended up at the login page, I do a location.reload() to reflect this on the page. That's just another option if you go that route, it looks like this:
$.ajaxSetup({
complete: function (xhr) {
if (xhr.getResponseHeader('LoginPage') == "1") {
location.reload();
}
}
});
Without knowing what server platform you're using I can't say how to set headers, but it's pretty easy on every common platform.
You should use firefox and download a program called 'FireBug'. This will show you all the requests being sent out, and the response that comes back from the AJAX call. It is action packed with goodness & web dev tools.

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