Παρασκευή 1 Οκτωβρίου 2010

How to make your old web application use ajax to avoid page refresh

The problem
Have you already implemented a web application that works perfect but it doesn't make any ajax request? User are bored of unlimited refresh that happens each time they press any link or button?

The solution

I have the solution! Simply use ajax to make your request, the way you are used to and implement success function to update your pages' root element[1]!

Some code

1) Simply add the following JavaScript function in your js library:

function ajaxReq (requestURL, what2change){
$.ajax({
url: requestURL,
cache: false,
async: true,
dataType: 'html',
success: function(html){
var x = $(html);
$('#'+what2change,x).each(
function (i) {
document.getElementById(what2change).innerHTML=this.innerHTML;
}
);
}
});

And use it writting something like the following:
a) <input onclick="ajaxReq ('index.jsp?param1=2','root')" type="button">
b) <a href="http://www.blogger.com/post-edit.do#" onclick="ajaxReq ('index.jsp?param1=2','root')">

[1] In most cases you have some div or table that contains the part of the page that changes in each refresh. This should have a specific id the value of this id should be set also as value of the variable 'what2change' in the ajaxReq function.

Additional Information
If you use JavaScript that runs while your page is being rendered, then you should also read my new post "How to run JavaScript after sucessful completion of Ajax request" that is based on the articles http://www.developersnippets.com/2009/05/20/evaluate-scripts-while-working-on-ajax-requests/ and http://www.linein.org/blog/2009/06/05/run-javascript-code-after-an-ajax-request/

Δεν υπάρχουν σχόλια:

LinkWithin

Blog Widget by LinkWithin

Mobile edition