In traditional javascript AJAX, we know if readystate is:
0 - The request is not initialized
1- The request has been set up
2 - The request has been sent
3 - The request is in process
4 - The request is complete.
When it comes to jQuery AJAX, we have:
complete property where we code what should happen after completion
success property where we code what should happen if the ajax request succeeds and
error property where we code what should happen if ajax request fails.
All of the above properties lets us code to do something after completion of ajax request. Where can I specify some code to execute something during processing(when readyState is 3) in Jquery Ajax??
As my AJAX script takes too long time to execute, which means, I will not attain 'complete' stage quickly. This seems like nothing is happening to the user. I wanted to initiate another ajax script at processing stage which gets information from server meanwhile and shows the user what has been done so far. Is it possible at all in Javascript? I know there is no multi-threading in Javascript.
I think I made my self clear. But, Please let me know if anything is not making any sense.
I handle this by initiating the first long running request, returning to the user immediately and allowing the process to fork server side for the extended processing.
The initial return ajax call to the user sets them up to 'watch' that process via a flag against the object ( I store them against the object in the database, but you could for instance watch file sizes or other stuff )
Subsequent ajax calls occur in a loop, each one returning setTimeout for the next call, and report on changes to that flag so the progress of the long running process is then visible. Completion of the long running process prompts NOT sending another setTimeout() and showing the overall results.
If your process is not that intensive, a simple spinner would probably do the job and no work for your server process. I usually handle that having $.ajax flip the visibility of a 'spinner' icon that's preloaded on my pages in the same spot for all.
According to jQuery's Ajax documention, they do not expose the readystate change event:
No onreadystatechange mechanism is provided, however, since success,
error, complete and statusCode cover all conceivable requirements.
It would be possible to show a loading image after the initial Ajax request is kicked off (and before getting any "complete" or "success" events, and then start polling a different URL via ajax which will give you the status of the first request, assuming your server can show progress of the long process before it completes.
Related
I would like to have a spinner appear when a form has been submitted and then be replaced by a checkmark to indicate the operation has been completed. I already have JQuery detect when the button has been pressed and make the spinner appear like so:
$('.scrape').on('click', function(){
$('.spinner').removeClass('hidden');
})
How can I have the client/server side detect that the operation has been completed? An AJAX call wouldn't work because the POST request has already been made, right? Note: I am working with the express framework. I'm not rendering anything because it's all on the same page.
Thanks!
Each time you make a request to your server, you should get a response from the server. Receiving a response with a non-error HTTP status means your operation succeeded.
"How can I have the client/server side detect that the operation has been completed?" You mean client. The client ultimately controls what is displayed on the screen, so the client needs to know when it's time for the checkmark. (So I don't care that the server is a NodeJS process using express.)
"An AJAX call wouldn't work because the POST request has already been made, right?" But you must have an handler somewhere for the completion of the request. You haven't said whether you're doing this by $.ajax or vanilla javascript or something else, but whatever you're doing, you just need to add something to that handler so that it adds the checkbox. If you want a more specific answer, feel free to share some more code :-)
I'm using Aurelia and have multiple promises calling my API. If I continually click the button to fire the promises over and over and over again the back end will timeout. How can I stop/halt the promises I am firing and just get the newest one so as to not over work the API and cause a timeout?
This is not specific to aurelia, it happens with any asynchronous event implementation.
When you click on a button, the event handler is called.
The event handler sends an asynchronous AJAX request to your server. Because it's async, your code and your application continues to run while the request is happening.
User can click again on the button and a second AJAX request can be sent at the same time, assuming that you click faster than requests complete.
To make it worse, concurrent requests may even complete out-of-order (i.e. a later request completes before a former). Your code should be prepared to handle that properly.
If you don't want this behaviour, it is up to you to prevent the user from submitting again until the AJAX request completes. For example you could:
Disable the button when sending the request; or
Display a modal "loading" screen / spinner to prevent any interaction with the application while the request is in flight.
Note that giving user feedback is good UX anyway. A network request might be delayed for a whole lot of reasons and it is a good idea to give some feedback to let him know that something is happening.
I have an AJAX call that is running a long PHP script where it has 20 different results, I would like to show when each step in the script is done.
Like so 1/20 done, 2/20 done, 3/20 done.
Latest 29-12-2015 03:17.
I tried to create the JSON file as so (jsonFileName_uniqueTimeStampHere.json) by PHP, but the time taken to create the file with PHP, result in a 404 file not found error!
Because when the AJAX call is running it comes to the progress call before the file has been created, I know I can't create the file with JavaScript but is there anyway to create.
The file before the success callback from jQuery AJAX?
What would be the best way to show progress information while AJAX call is running.
The way I have it now, I have a JSON file saved on the server that gets updated with the latest state that has completed, but if multiple users is running the same script the JSON file with the state gets overwritten.
Should I save the state of each progress in DB and then receive it with multiple calls to a PHP method that get state that has been completed?
Should I keep using the current method I use and add a userID to the JSON file so it is unique on each call to the file?
How should I go about doing it the same way as Seositecheckup?
What is the best way to make a progress with AJAX and PHP?
Please tell me if you need any more information.
I have looked around and don't feel like the info or half of info, there is to find online has been enough to do this myself.
I would like to use jQuery AJAX and not XMLHttpRequest, I'm looking for something similar to seositecheckup.com, when you scan a page you can see the state update on each completed function in the console and is done with different AJAX calls. How is that possible?
Should I forget about using jQuery and keep focus on plain JavaScript instead?
Right now I have a setup with jQuery that works the problem is, that I use a JSON file to get the result from and it gets overwritten when multiple users request the same script, is it possible to store the state in db instead and receive it from there with some unique identifier?
In the future I would like to make it possible to put the script into a queue that could be run and when the script ends it should send an e-mail to the user.
The HTTP way of handling requests that may take a long time is for requests to return a 202 and the body of the response should contain the URL where the user can query for the result.
#Request
POST /some/entitities
...
#Response
HTTP/1.0 202 Accepted
/jobs/{jobId}
The user can then poll /jobs/{jobId} which can return a number to represent progress. Do you have to use this? No, but if you do, others developers can immediately recognize what is going on.
Even if you don't use the approach I recommend, you will also have to keep track of job progress in your database and have a separate AJAX call to find out the current progress.
I'm trying to show a popup in the middle of the screen while my website talks to my AJAX server. Since some of the operations take a couple seconds to do, I want to give my users a visual cue that an operation is occurring. For example, you can create a music playlist on my site. When the playlist is being created, I want a div to popup saying it's creating the playlist on my servers.
I made a jsfiddle to show the functions I'm using to try to produce this, but I'm having a bit of an opposite effect. In the fiddle, it shows the popup after it tries to talk to the server (it will fail to talk to the server because I deny anything outside my domain), but since it fails to talk to the sever, it never calls hide_popup().
On my servers, it never even shows the popup (unless I call an alert() directly after the show_popup() call).
I'm not sure why this happens, but I simply want to
1. Show the popup
2. Execute my AJAX-call
3. Hide the popup
Any suggestions?
There are a few problems with the way you wrote your code. Here are a couple of them:
(1.) Call:
var response = get_server_response("action=createPlaylist&name=" + name, false);
You are expecting a response immediately which will not happen with an AJAX call. Moreover, you are passing false for the async parameter, which is making it effectively a sync call. This is why your code is just waiting before doing anything else.
(2.) Implementation:
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
response = xmlhttp.responseText;
}
}
xmlhttp.open("POST", ajax_server, async);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(url);
return response;
You are only caching the result in response and not processing it while tracking onreadystatechange. You are actually processing it just after the call which will execute after the call and not on receiving the response. No need to return the response here.
(3.) popup:
You are not using show/hide at an appropriate place.
Solution:
I would suggest you fire a callback while tracking the onreadystatechange by implementing a function. Show the popup just before you make the network call. Hide it inside your callback function depending on the readyState and status.
Here is a working fiddle for you: http://jsfiddle.net/nDNXc/549/
Hope that helps.
First I recommend you to use a common library for your Ajax calls, e.g. jQuery.ajax.
Second learn about asynchronous Javascript. Your call of get_server_response() returns immediately without waiting for your Ajax request to complete. Have a look at the complete parameter in jQuery.ajax. It accepts a function that is called when your requests completes - the right place to hide your message!
If I have a JS function as follows;
function testFn()
{
x.ajaxMethod(param1,JScallBackFunction); //Please do not worry about the syntax..this just indicates an external method call
alert("Line after ajaxMethod");
}
The ajaxMethod(), lets say is some kind of method defined in an external Java file (so it can be through DWR or anything) which returns some data...Point is it takes some time to execute this line of code...
Now my question is when will the alert on next line get fired (i.e. alert("Line after ajaxMethod");)
Will it wait for these 2 things to complete (ajaxMethod execution as well as JScallBackFunction)
OR
It will be fired immediately without waiting for any of the above 2 things to complete ?
Also if you could guide in general about the JavaScript method flow execution, that will be great.
It depends. Ajax calls are usually asynchronous which means the execution of code will not be paused until the asynchronous function returns. Therefore the alert will be executed immediately.
Asynchronous functions in javascript are usually to do with Ajax and loading something from a remote server. If you do wish to force JavaScript to wait while loading that content then you can set a flag for the XMLHTTPRequest object.
this is a good question to read: When is JavaScript synchronous?
it will fire immediately after the ajax call. if you want it to wait put it in the callback function.
edit: a method that defines a callback is essentially this:
function(param1, callback) {
// do stuff
callback(); // execute callback
}
First, when you say
The ajaxMethod(), lets say is some
kind of method defined in an external
Java file
I suppose you really mean external JavaScript file.
When you send an Ajax request, you ask the browser to send a request to the server for you.
This request on the server may take sometime and you don't want to "wait" on it. (This is the whole idea of Async requests - stuff in the background).
So you tell the browser, here send this request to the server. Don't bother me unless the server responds, and once the server responds (we have a "response"), call this method. This is called callback. The method is called at a later point, when the response comes.
So the statement
x.ajaxMethod(param1,JScallBackFunction);
(assuming that it does gets a XmlHttpRequest, initializes it and calls the send method on it*) actually does two things:
Sends the Ajax request
Registers a call back function that will be called when the server responds (when we have an response). JScallBackFunction will be called when there is an response from the server.
But since this is an asynchronous request, the browser does not "wait" instead it continues to the next statement (if there is one) after the Ajax call and executes it.
So, alert("Line after ajaxMethod"); will be executed immediately.
*If this does not make any sense for you, this is how an Ajax request is actually "created" and "sent". This article may help you understand.