All about AJAX – From Beginners to Experts – Part 1

Brief History of Web Development

Let’s go 18 years back 1996, We have just started to create web pages, static with text, static with images and wowed the world. The browser was in demand to display web pages which render HTML. Later on using Perl or C dynamic content has started to serve to a browser. As HTML and Browser evolved, Web becoming interesting, to stream video, playing games, online chatting, pay the bills, find a date and lots of other fun/work activity.

Flash Player was the key part in 2000 to the 2010 year. By using it, Advertiser has started creating animated ads and born of Rich Internet Application. With the use of Adobe Flex technology and instantly became famous. But Flash Player is not supported by Apple on Mobile devices and HTML 5 seems promising.

HTML 5 has gain popularity and started to use as to make Richer Internet Application using JavaScript and it’s framework introduced by many giants. i.e JQuery, DOJO, Backbone, Sencha , Angular.

New Trend came and that’s Single Page Application without refreshing the page, render dynamic data like Gmail does. To get data, Browser needs to send the request to the server using JavaScript and that’s called AJAX.

Brief History of AJAX

Microsoft has introduced Internet Explorer to beat Netscape Navigator and got succeed. IE become the world famous browser and introduced many functionalities like ActiveX and Iframe to load asynchronous data. In 1998 IE introduce XMLHTTP for outlook web app. Another browser like Mozilla, Safari has introduced XMLHttpRequest and IE has supported in IE 7.

JavaScript was not widely supported and trusted language in those days. So the world was adopting Adobe Flex to develop Enterprise Rich Internet Application and it grew a lot in 2007-2008. In 2010 Apple wrote a letter in regarding supporting flash player in Iphone, IPAD and IOS supported devices and that was not a good news for Adobe for more info click here. From that day the Big company would hesitate to build an application in Flex and search for new approach rises.

Google continued to develop an application in that approach and gave the world GMail, GMap, Google+, Picasa etc using AJAX and others followed.

What is AJAX?

AJAX stands for Asynchronous JavaScript and XML. AJAX is a technique to send the request and get data asynchronously with the refreshing web page which happens in the traditional application like Wikipedia.

With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. – Wikipedia

XMLHttpRequest is used to make a call to server and retrieve the data. It’s an API provided by the browser to support AJAX technology.

This JavaScript code is to make ajax call to server.

function myAjax() {
 var xmlHttp = new XMLHttpRequest();
 var url="serverStuff.php";
 var parameters = "first=barack&last=obama";
 xmlHttp.open("POST", url, true);

 //Black magic paragraph
 xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 xmlHttp.setRequestHeader("Content-length", parameters.length);
 xmlHttp.setRequestHeader("Connection", "close");

 xmlHttp.onreadystatechange = function() {
  if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
   document.getElementById('ajaxDump').innerHTML+=xmlHttp.responseText+"<br />";
  }
 }

 xmlHttp.send(parameters);
} //from stackoverflow

Here is the php code.

<?php
 //serverStuff.php
 //from stackoverflow
$lastName= $_POST['last']; $firstName = $_POST['first']; //everything echo'd becomes responseText in the JavaScript echo "Welcome, " . ucwords($firstName).' '.ucwords($lastName); ?>

And here is HTML code.

<!--Just doing some ajax over here... from stackoverflow-->
<a href="#" onclick="myAjax();return false">
Just trying out some Ajax here....</a>
<br />
<br />
<span id="ajaxDump"></span>

This is an example without any framework or library. Just plain JavaScript.

In next blog, it will be in more detail to make a different kind of ajax call with JQuery.

 

Accessing instance method of JavaScript using this keyword inside each()

As a Java or C# developer, this keyword can we be used in instance method or in constructor to access variables or instance methods.

JavaScript is a prototype-based scripting language and supports Object-Oriented features and this keyword too.

JQuery is most popular JavaScript Cross-Platform library and 99.99% developers uses it for web development. JQuery has $.each() to iterate jQuery object.

Like

var sum = 0;

var values = [ 10, 20, 30, 40, 50 ];

$.each( values, function(){
sum += this;
});

console.log( sum ); //sum would be 150

In above example, when elements iterate with each, it create dynamic object inside the method named this. Now using this object we can have the access of each element. in this example using this we can get the value.

How this can be used in Javascript class. Here is the example.

function Employee (position,name) {
    this.position = position;
    this.name = name;
    this.getInfo = function() {
         return this.name + ' ' + this.position +" earns "+this.getSalary();
    };

    this.getSalary = function(){
      return "$10,000";
    }
}

var employee = new Employee("Spy","James Bond");
console.log( employee.getInfo() );  // James Bond Spy earns $10,000 

Now what if we use $.each() in Javascript class and want to use <strong>this </strong>keyword as Javascript class’s instance as well as to get element in the $.each iterator?

function Employee (position,name) {
    this.position = position;
    this.name = name;
    
    this.getInfo = function() {
        return this.name + ' ' + this.position +" earns "+this.getSalary();
    };

    this.getSalary = function(){
      return "$10,000";
    }

    this.printInfoIfSalary=function(salary){

      var salaryList = {"Manager": 20000, "Spy": 10000, "mentor": 5000};

      $.each( salaryList, function(key){
          if(salary==this){

           //Now what If I want to call getInfo from here   
            this.getInfo(); //Wont Work
            getInfo(); //wont work

          }               
      });
    }
}

var employee = new Employee("Spy","James Bond");
console.log( employee.getInfo() );  // James Bond Spy earns $10,000 
employee.printInfoIfSalary(10000);

When employee.printInfoIfSalary(10000) executed, there is no way using this or with this to call getInfo() method within each method of jQuery and it will throw uncaught TypeError: undefined is not a function.

using this Uncaught TypeError: undefined is not a function

How can we fix this? I have spent more than 1 hour to solve this problem. but finally I figured it out. Here is working code.

Working code to fix above issue.

function Employee (position,name) {
    this.position = position;
    this.name = name;
    //define thisObj as globle variable and give this reference
    //now thisObj can used as this if class instance
    var thisObj = this;
    this.getInfo = function() {
        return this.name + ' ' + this.position +" earns "+this.getSalary();
    };

    this.getSalary = function(){
      return "$10,000";
    }

    this.printInfoIfSalary=function(salary){

      var salaryList = {"Manager": 20000, "Spy": 10000, "mentor": 5000};

      $.each( salaryList, function(key){
          if(salary==this){
        
          //Now what If I want to call getInfo from here   

          console.log(  thisObj.getInfo() ); //will Work

            //getInfo(); or this.getInfo() //wont work
          }               
      });
    }
}
var employee = new Employee("Spy","James Bond");
console.log(employee.printInfoIfSalary(10000));

In this example we define thisObj = this, reference of this variable to thisObj, and now thisObj can be reference as instance of this class.

I hope this example with help you to understand when jQuery and OOPs concepts needs to use together.

Code for this example:  http://codebeautify.org/htmlviewer/e1ce80