Track Ajax requests on a page - javascript

I have a web page and I am associating a note with the page storing it in my database, so that the whenever the next time the page is loaded that notice can been seen till it is deleted by some other user authorized to do the same. However, say I associate a note with the page after some content is loaded through AJAX. I want the note to appear only after that particular content has loaded next time on the web page. I would like to track the AJAX request and attach the note to it? I want to do it all through simple JavaScript code put at the bottom of any web page. How can it be done?

jQuery ajax provides methods to fire events before, during and after the ajax request. Please check the api here for complete list.
Here are couple of methods that are called after completion of every ajax request.
jQuery.ajaxComplete() - Register a handler to be called when Ajax requests complete.
jQuery.ajaxSuccess() - Show a message when an Ajax request completes successfully
These functions allows you to pass a callback function to trigger after event occurs. In that call back function check if content you want is loaded or not, then show the note.
Sample code for the above methods can be found here:
http://api.jquery.com/ajaxComplete/
http://api.jquery.com/category/ajax/
Hope this helps.

You'd need to write a wrapper for all of your ajax calls that checks the result and sees if it should add a note. Here's an example, assuming you're using jQuery to handle the ajax requests:
function ajaxWrapper(settings){
var old_callback = settings.complete;
settings.complete = function(request, status){
if(status == "200"){
// check the request.responseText and add your note if appropriate
}
if(old_callback){
old_callback(request, status);
}
}
jQuery.ajax(settings);
}
And then instead of calling jQuery.ajax() directly, call ajaxWrapper() instead.
An alternate option would be to include the note in your ajax response.

Related

I need to create a post in the webpage without refreshing the page using ajax

In my webpage, the user can write a post and the data the user enters is then stored in the database. I want that data to be Selected by a query and posted into the webpage but without the page being reloaded.
I am aware that I need to use Ajax, but I do not know how to use it. I need the post to be added to the page when the post button available in the webpage is clicked.
If you do not know how to use it, why not try to read up on it? :)
To give you a gist of what you need to do, the button needs to be tied to an event handler in Javascript/JQuery. That event handler will be responsible for making the AJAX call and retrieving the information from the server. The call would be something like:
$.ajax({type: 'GET', url: '/path/to/information'})
Calling .done() on this particular AJAX call will execute the callback function specified in the parameter. Usually it's done like so:
$.ajax(...).done(function(data) { ... });
Where data is the response data on a successful (200) response. Once you receive the data, you would just use Javascript to update the html/text of an element on the DOM. How you implement this is solely up to you, but I suggest reading up and trying to get it to work before asking!

Using Data Generated from AJAX Call for OnClick Event

I have a web application where I want to get some data from an API right when the document is ready to execute javascript. I want to store this data in an Object for later access. When a user clicks on a certain link on the page, I will need access to this Object.
I'm wondering what the safest/most accepted pattern for achieving this is, since it involves to events to listen for (the success of the AJAX request and the later possible click). I don't really want to wrap all of my code in the AJAX request if I don't have to, but I also don't want to run the risk of the user clicking before the AJAX request has finished (it's a fairly small API call, but still).
Deferred objects to the rescue!
(function($){ // this prevents polluting the global scope
var request = $.ajax({...});
//... later on...
$(someelement).on("click",function(){
request.done(function(data){
console.log(data);
});
});
})(jQuery);

Show "In Progress" during http request (long running) execution in javascript/jquery/php

I would like to have "Loading.." / "In Progress.." message during regular http request. This should be shown only during the http request cycle, and once you get the request is completed and you get the response, it should go off. I am keen about regular HTTP Request, and HTTP Request that take longer time and not AJAX. Code blocks, examples, pointers appreciated. Here is one approach, I would like to have common approach, so that it can be used for any http request.
You should use beforeSend and complete events:
$.ajax({
...
beforeSend: function(){
//Here you loading SHOW
},
complete: function(){
//Here you loading HIDE
}
...
});
Basically when executing a normal HTTP request (not AJAX), the client browser already provides a progress indicator. This indicator will vary between browsers and platforms and you cannot rely act on it.
Your javascript stops working once you navigate away from the page so don't look for a javascript solution to show such progress indicator. Depending on how this HTTP request is triggered there might be different ways to achieve that. For example if you have an anchor tag in your markup that triggers a normal HTTP request, you could subscribe to the click handler of this anchor and show an animated spinner using javascript and then let the browser do the redirect.
And as far as AJAX requests are concerned you could subscribe to the .ajaxStart() and .ajaxComplete() global handlers to respectively show and hide some spinner.
Of course everything will depend on the implementation. There's no magic solution that will handle all the possible cases. So basically you will have to find a solution that's adapted to your specific context which unfortunately you haven't detailed.
You could have an element on the page that gets hidden once the page has been fully loaded. E.g.:
<img id="loading" src="loading.gif" alt="Loading..." />
<script type="text/javascript">
$(function() {
$('img#loading').hide(); // Called when whole page has been loaded
});
</script>
I think it is not possible to render any information during pure javascript HTTPRequest synchronous call (not the case in JQuery). If you change a style, class.. just before calling the send method, this info will not be rendered.
To fix this issue, I changed call to asynchronous call, then the style, class .. changes can be rendered before the call returns (using onreadystatechange to get the result and reset style)

Dynamic page fetching with AJAX

i have a question regarding partial page loading with AJAX.
Suppose that an user clicks on a button that makes an AJAX call to load part of a page (it can possibly include dynamically loaded JS and/or CSS), and the html content is dropped on some div. Then, before the first load is complete he clicks on another button that makes another AJAX call that drops other content on the same div. How should i prevent this behaviour to create any conflicts? Some possible conflicts might be something like, for example, the first load executes some JS on content that is not found because the second load already changed that div.
Thanks in advance.
Edit:
I would appreciate answers based on asynchronous methods. Thanks.
Genesis and Gaurav are right about disabling user interaction. +1 from me to each of them. How you handle the logic is actually quite simple:
$('#my_submit_button').click(function(){
$.ajax({
url:'/my_file.php',
dataType='json',
beforeSend:function(){
$('#my_submit_button').prop('disabled',true);
},
error: function(jqXHR, status, error){
// handle status for each: "timeout", "error", "abort", and "parsererror"
// Show submit button again:
$('#my_ajax_container').html('Oops we had a hiccup: ' + status);
$('#my_submit_button').prop('disabled',false);
},
success:function(data){
$('#my_ajax_container').html(data);
$('#my_submit_button').prop('disabled',false);
}
});
});
make it synchronous (not recommended)
disable link/button while ajaxing
do not mind about it
but in your case it won't do any conflicts because when html is replaced, scripts too
Just disable the buttons that cause the AJAX calls to start while one has not completed yet.
I'm not sure this would actually be a problem for you because Javascript is single threaded. When the first ajax response comes in and you execute some javascript, that javascript cannot be interupted by the second ajax response as long as it is one continuous thread of execution (no timers or other asynchronous ajax calls as part of it's processing).
Let's run through a scenario:
User clicks button - first ajax call starts.
User clicks button - second ajax call starts.
First ajax call finishes and the completion code execution starts for what to do with the new data.
While code is executing from first ajax call, the second ajax call completes. At this point, the browser puts the second ajax call completion into a queue. It cannot trigger any of your completion code yet because the Javascript engine is still running from the first load.
Now the first load completes it's execution and code and returns from it's completion handler.
The browser now goes to it's queue and finds the next event to process. It finds the completion of the second ajax call and then starts the completion code for that ajax call.
As you can see from this scenario which has overlapping ajax calls and the second completing in the middle of the processing the first, there still is no conflict because the Javascript engine is single threaded.
Now, as the other answers have suggested, you make not want this user experience of launching a new request while one is still processing, but they won't technically conflict with each other. You have several tools you can choose from if you want to prevent overlapping calls:
You can prevent starting the second call while the first call is unfinished. You can do this both in the UI and in the actual code.
When there are multiple calls outstanding, you can decide to drop/ignore the earlier responses and not process them - waiting only for the last response.
When the second call is initiated, you can cancel the first call.
You can let the second just replace the first as in the above scenario.
The first two options require you to keep track of some cross ajax-call state so one ajax call can know whether there are others and act accordingly.

Kill JQuery AJAX overlapping requests

Is it possible to kill a previous ajax request?
We have tabular data very adjacent to each other. On mouseover event of each data we are making a request to our server using JQuery Ajax object and showing in popup.
But as frequently we move mouse to other tabular contents previous Ajax responses are being displayed inside popups prior exact response being displayed which is meant for that tabular content.
I need when new Ajax request is generated previous request/response should be killed, so that always expected latest response is available inside popup.
I am using JQuery, PHP and Mysql to server the request.
Could you create a custom Javascript Sync object which would be shared by the function making subsequent ajax calls?
Assign a sequentially generated id as a parameter to the request call going in. Include the same id in response. On firing every request assign a new id, incremented by 1 or whatever logic. If the current id in response is not same as the one in shared object; ignore the response else render the response.
this would cleanly solve the race condition. I am not sure myself if there is a way to kill the request prematurely but it would at least not create rendering problem that you face now.
Another option would be not to initiate another request until the first is completed.
Yes and no. That is the point of Ajax. To be able to do something asynchronously. What you are wanting to do is to abort a request which destroys the idea of asynchronously. Perhaps what you can do is, if you send another request, set a value somewhere indicating the number of requests, then in the callbacks to your requests, check if the amount of request is higher than 1, if so ignore the response.
Check this AJAX Manager plugin. The XmlHttpRequest has an abort() function but jQuery doesn't have a wrapper for it.

Categories

Resources