S. Kiragu S. Kiragu - 1 year ago 47
Ajax Question

Create a reusable function to open and send Ajax

I have noted that in my program every time when I want to declare a object, for example list, save, add, remove I write the following every time in each function.

ajax.open("Get", "./route/action",true);

I want to do something like this.

./route/action // this is path to my Action class-using servlet

Every time I have to open a connection, give the path to my action class which is a
and then send. I do this every time I want to load a list, delete or update.

How can I write a function that I will be just be:

// 'ajax.content' is the id of the div where I
// want to show the list,where after updating AJAX show the update list to the user.

For example after adding a user I can see the added user without reloading the whole page. I am working on a maven project using Java EE, Servlet and JavaScript.

Answer Source

Try this:

function ajaxRequest(AJAXurl, callbackElementID){
   x = new XMLHttpRequest(); 
   x.open("get", AJAXurl, true);
   x.onreadystatechange = function() {
    if (x.readyState == 4 && x.status == 200) {
     document.getElementById(callbackElementID).innerHTML = x.responseText; //Will send the received data to the element passed in the function

Use as following:

ajaxRequest("/somefile.php", "elementID"); //This will send recieved data to the element with "elementID" as id

Note: The way this is built is only for GET requests. Change code if you want POST request.