views:

104

answers:

2

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?

A: 

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.

nFriedly
This requires changing every ajax call to use the wrapper. jquery's ajax wrapper already provides that functionality so you can be notified of every request, as noted by Uttam
Juan Mendes
Yes, but the original question didn't specify that he was using jQuery. This is a general response that could be used with any AJAX library. If he is using jQuery, however, then Uttam's answer would be a better choice.
nFriedly
+1  A: 

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.

Uttam