I have a function that makes an ajax request to write some data to a database.
Yet, when for some reason, the function is called more than once on the page (which sometimes seems to happen), I check via javascript how often the function was called and the ajax request is not executed if it was called more than once to avoid adding data twice.
However, since the ajax request is never executed in this case, the .done function does not work anymore, which breaks the functionality of the script further down the line.
My workaround is, if the function was already called, to make an 'empty' ajax request in which I do not transfer any data to the PHP script on the server-side.
This way, I can still use the .done function and execute the rest of script normally (without adding any duplicate data).
Is that a sensible way to deal with such a case?
It seems to me that it is a waste of server resources, since there is no need to communicate with the server in this case.
Is there a better way to make an "empty" ajax request, such that the .done function can still be executed?
Related
I know this question has been asked multiple times before as how to execute function when all AJAX call has been completed. We can user jquery.stop() in this case.
But my requirement is different. I want to show confirm banner when all ajax call have been executed successfully. For different pages , I have multiple AJAX calls. I do not want to put any condition on each AJAX call success method.
Can any one suggest if there is any global way.
Thanks in advance.
your are searching for global event handlers:
https://api.jquery.com/category/ajax/global-ajax-event-handlers/
http://api.jquery.com/ajaxcomplete/
anytime when you call an ajax request you "see" it via .ajaxSend() and handle response via .ajaxComplete()
I've got a general question about AJAX. Is it okay to send JavaScript in an AJAX response and execute it? Or is the only elegant way to respond either with JSON or plain HTML?
My problem is that I am searching for the best way to handle AJAX requests which are leading to the insertion of HTML OR the execution of JavaScript, depending on user data.
Thanks a lot.
I would think that the JavaScript function that would be executed after the AJAX response would be standard for everyone aside from some variable. If that is the case, you should include the JavaScript function in your scripts file that gets loaded normally in the . Then have the AJAX response come back with the variable that you need, like the user ID. Then use that variable to call the JavaScript function normally instead of injecting a new function each time.
If HTML is returned you can insert it directly into the DOM on a successful AJAX request.
I think the way to go would be to always return JSON even if it's an HTML response. The JSON response could be something like:
{"responseType":"HTML", "varID":null, "payload":"<div>some html</div>"}
If the response were type JS then the varID could have that variable and the payload could be null. That's just an example but you could do something similar to standardize the response but handle both scenarios.
No it's ok to do so, in jQuery $.getScript do just that, it get the file via ajax and then evaluate it. Which is why no script tags are ever added when using getScript
Executing javascript received by an ajax call is a bad idea as this can lead to XSS style attacks (eval is evil and all that jazz).
An AJAX response is best served up in JSON format and then the client side scripting can act in accordance with the JSON it receives.
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.
I am trying to write a Perl script that will take a user parameter from command line and with his parameter, Perl script will call a JavaScript function in a HTML page. How can I go ahead to with this?
Not that I've seen. Perl is strictly server side, and JS functions you're talking about are on the client.
The closest you would get is have the Perl script write a block into the HTML page so that the page fires it on load to perform the action. But that's a little shaky at best to do.
It depends on whether the browser or server will be taking the first step.
If the server needs to run code first and then execute some JS, then #skyburner's solution would work. Essentially you would already have some functions defined on the page, but then you would dynamically add a block of JS to call whichever function you need to.
However, if the Perl is being run due to a user's action on the current page (such as clicking something or submitting a form), then AJAX would be the way to go. You would use JS to submit an HTTP request to the Perl script. The Perl would then return some value back to the JavaScript and execute some function based on this result. This would all happen "behind-the-scenes" without the user leaving the page.
If I understand correctly about what you want, since not all the browsers support socket, this is what you can do:
Have an ajax service call periodically sending requests to the server for update
Once the the parameters from the command line are taken, you can send the result along with an ajax response back to the page, and call the function in the ajax request callback function.
Also, another option, you can use reverse ajax to accomplish this. See Wikipedia about reverse ajax (comet), especially Ajax with long polling.
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.