Click here to Skip to main content
15,890,579 members
Articles / Programming Languages / PHP
Tip/Trick

Simple Dynamic JavaScript Ajax Function

Rate me:
Please Sign up or sign in to vote.
4.09/5 (5 votes)
25 Jan 2019CPOL3 min read 11.8K   148   8  
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)


Written By
Team Leader ArabicRobotics.com
Egypt Egypt
Tareq Gamal El-din Mohammed,
---------
Website:
www.ArabicRobotics.com

---------

Graduated from Modern Academy for Computer science and Information Technology. Egypt,
Then flow Microsoft development track Certificates:
MCAD.NET (Microsoft Certified Application Developer)
MCSD.NET (Microsoft Certified Solution Developer)
Microsoft SharePoint Administration, Configuration and Development.

Robotics fields was a Hobby since 2002,
started to develop some applications for "Robosapien", "RoboSapienV2", "RS Media", RoboMe and WowWee Rovio. from WowWee company,

Started working with robots as a professional way at 2014
By using "NAOqi" Robotics from Aldebaran.

By developing some applications and libraries like :
NAO.NET.
https://www.youtube.com/watch?v=oOyy-2XyT-c

OpenCV with NAO Robot:

- NAORobot Vision using OpenCV -TotaRobot P1
https://www.youtube.com/watch?v=MUcj8463x08

- NAO Robot Vision using OpenCV - P2
https://www.youtube.com/watch?v=93k1usaS-QM

NAO Alarm Clock :
https://www.youtube.com/watch?v=djLlMeGLqOU
-----------------------------

also Robotic Arm Project:


Other Projects Developed by Tareq Gamal El-din Mohammed :

Developed and posted some applications in Code Project web site like :

- Control your Distributed Application using Windows and Web Service
http://www.codeproject.com/Articles/101895/Control-your-Distributed-Application-using-Windows


- Quick and dirty directory copy
http://www.codeproject.com/Articles/12745/Quick-and-dirty-directory-copy

- Program Execute Timer(From the Web)
http://www.codeproject.com/Articles/12743/Program-Executer-Timer

Comments and Discussions

 
-- There are no messages in this forum --