Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PHP

Simple Dynamic JavaScript Ajax Function

4.09/5 (5 votes)
25 Jan 2019CPOL3 min read 12.4K   148  
Simple compact reusable native JavaScript function, you can use it easily in your web Pages to run Ajax Enabled and avoid refresh

Image 1

Introduction

Usually, Ajax and JavaScript are hard to develop or understand for beginners. Also, it needs to be written by more code.

Using only one function AjaxCall() enables dynamic functionality to run Ajax on webPages. It allows beginners to run Ajax code on any web page without additional code or external libraries. It is useful to simplify and run Ajax requests as simple as possible with maximum flexibility.

Background

In my last project, I wanted to design and develop "one page design" and it should be fully functional, connected with backend without any client-side refresh. after several trials and optimizations, I reached this JavaScript function to optimize Ajax call which can be used for any web project. So I decided to share it with the world.

Using the Code

To describe the function AjaxCall(), I will divide it into three parts:

  1. parameters
  2. body
  3. Call

Here are the details:

1. Parameters

Before going in depth, you can just call the function using for example:

JavaScript
AjaxCall("ServerPage.php")

Only one mandatory parameter which is serverFile Parameter1: serverFile: This is the file which will be called when Ajax runs. It will contain: Filename and parameters like: “FileName.php?id=111&y=222” and so on.

For other parameters:

Parameter 2: ControlId: control Id is the control you need the result to be displayed at: “innerHTML attribute

Parameter 3: attName

  • empty ('' ): Ajax will run but the result text will not be displayed.
  • not Empty: If you need the result to be filled in Attribute like “BG-Color”, class, etc.

Parameter 3: callId: Identification variable for this call, so you can know which feedback is for which request. this call id will be included in the function as well.

Parameter 4: Device: (optional) If you are using one parameter repeatedly, like: categorization to make it easier to let you control the output place in your page so you can write it in device ...

Parameter 5: Async: This is the calling type of Ajax. By default, it will be Async, which means the page will not wait for the response from the server, which means your code will never hang because of Ajax. But in some cases, you need to make it false because all the applications may be based on this call, so it should be false in those cases. By the way, I do not recommend to make it false.

Parameter 6: Timeout: This is the time to wait for the Ajax to return result from the server
Default value: 5 seconds

2. body

Here is the full body for the function, AjaxCall().

If you are interested in seeing the details of the body, you can take a look at the comments.

JavaScript
	function AjaxCall(serverFile=null,controlId=null,attName='', 
    callId='',device='robot',async=true,timeout='5000') {
    document.getElementById("divglobalstatuscontent").innerHTML="loading..";
    
  if (serverFile==''|| serverFile==null) {
      //"AjaxCall : ServerFile Empty"
      return;
  }        
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
        xmlhttp.ontimeout = function () {
        //addLog("The request TimeOut  "+serverFile);
             document.getElementById("divglobalstatuscontent").innerHTML="time out";
    };
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
        var address= this.responseText;
        if(attName=='')
            {
        if(controlId !=''&& controlId)
            {  
                document.getElementById(controlId).innerHTML = this.responseText; 
            }
            }
        else
            {
                 document.getElementById(controlId).setAttribute(attName,this.responseText); 
            }
         //addLog("AjaxCall: "+callId+"STATUS="+this.status+",VALUE="+this.responseText);
        
        switch(device) //if you filled the device , 
          // you can categorize the result into Divs in your page .. Here is some examples: 
            {
                    case("robot"):
                    document.getElementById("divrobotstatusbar").innerHTML = this.responseText;
                    break;
                    case("cam"): 
                    document.getElementById("divcamstatusbar").innerHTML = this.responseText;
                    break;
                    case("led"):
                    document.getElementById("divledstatusbar").innerHTML = this.responseText;
                    break;
                    case('notification'):
                    break;
                    case("move"):
                        document.getElementById("divmovestatusbar").innerHTML = this.responseText;
                    break;
                    case('global'):
                    break;
                default:
                    document.getElementById("divglobalstatuscontent").innerHTML=this.responseText; 
            }
         document.getElementById("divglobalstatuscontent").innerHTML="Success call";         
     return true;
    }
      else{
          
          //request failed.
          //document.getElementById("divglobalstatuscontent").innerHTML="...";
      }
  }
  xmlhttp.open("GET",serverFile,async);
  xmlhttp.timeout=timeout;
  xmlhttp.send();
}

3. Call

To call the function, you can simply use the code with any button or any control in the page, for example:

Example 1: Call Ajax with result to div

JavaScript
AjaxCall("backend.php?device=robot¶m=getConnectionStatus","divconnectionicon");

In this example, AjaxCall will call the file: BackEnd.php with some parameters.

Then, return the result to the page in divResult inner HTML attribute.

In HTML, you should have something like this:

JavaScript
< div id="divResult">  RESULT OF AJAX CALL < / div>

Example 2 (Class Attribute)

JavaScript
AjaxCall("backend.php?device=robot¶m=getConnectionStatus","divconnectionicon","Class",'global'); 

In this example, AjaxCall will call the file: BackEnd.php with some parameters.

Then, return the result to the page in divconnectionicon, in the attribute Class.

Result will be something like this:

JavaScript
< div id="" class="RESULT of Ajax call ">< / div>

History

For more examples and updates, you can check our GitHub Code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)