• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

jQuery Ajax Introduction

January 6, 2013 //  by Ganesh Prakhya//  Leave a Comment

As we already know, AJAX is a technique to update parts of a web page without reloading the entire web page. Ajax stands for Asynchronous JavaScript and Xml. jQuery supports AJAX functionality through various methods. Using jQuery AJAX methods we can request text, HTML, XML or JSON content from the server. We can send HTTP Get and HTTP Post requests using jQuery AJAX methods and also display the external data in the web page by loading the external data into the selected HTML elements.

also read:

  • Introduction to jQuery
  • jQuery Selectors : ID selector, Class selector and Element selector

If you are looking for a good book on jQuery, please buy jQuery in Action

We can have AJAX functionality without using the jQuery but we’ll have to handle browser compatibility issues on our own because each browser has different AJAX syntax and implementation. jQuery eliminates this problem by providing unified AJAX methods. This is one of the greatest advantages of using the frameworks which handles the problems of providing the browser compatibility, etc.

load() Method

The load() method loads data from remote server and puts the loaded data into the selected HTML element of the page. This method has three parameters, the following table summarizes the parameters.

URL The URL of the data to load.
data (Optional) request parameters. These are key/value   pairs we can send along with URL as part of the query string.
callback (Optional) function to execute after the load()   method completes execution. We specify the name of the function to execute.

The following code snippet loads the content from welcome.html file and displays it into the myDiv.

$(document).ready(function(){
  $("#myDiv").load("welcome.html");
});

We can also have optional callback method to execute after the load method executes successfully. The following code snippet loads the content from welcome.html just like above example and also has a callback function defined.

$(document).ready(function(){
  $("#myDiv").load("welcome.html", function(response,statusCode, requestObj){
    alert(response + '  ' + statusCode + '  ' + requestObj);
  });
});

Notice that the callback function in the above example has three parameters which represent the response from the load method call if load method call is succeeded, the status code of the call and XMLHTTPRequest object respectively. The sample run of the above code gives us the following output as shown in the screen capture.

ajax-callback

We can find out whether the call is successful by checking the parameter statusCode. For successful call the statusCode will be success whereas for failed call the statusCode will be error.

In case of error we can use requestObj.status and requestObj.statusText to find out the status of the failed request and reason for failure. The following is the sample code and output of a sample run with an invalid URL to load.

$(document).ready(function(){
  $("#myDiv").load("welcomeNotFound.html", function(response,statusCode, requestObj){
    alert(statusCode + '  ' + requestObj.status + '  ' + requestObj.statusText);
  });
});

ajax-callback-invalid

Thus we can have alternate functionality in case the requested URL is failed to load.

$.get() Method

The $.get() method sends a HTTP Get request to the specified URL and gets response back. The following snippet of jQuery code sends a GET request to the page welcome.html and prints the data and status using the alert box.

$(document).ready(function(){
    $("#btn").click(function(){
        $.get("welcome.html",function(data,status){
          alert("Data: " + data + "\nStatus: " + status);
        });
    });
});

We can also send some data along with the request optionally as shown below:

$.get("welcome.php", { username:"Some User", usertype:"Subscribed User" });

The following example also sends the GET request with some data and processes the response returned from the server.

$(document).ready(function(){
    $("#btn").click(function(){
        $.get("welcome.php",{username: "Some User", usertype: "Subscribed User"},
         function(data, status){
          alert("Data: " + data + "\nStatus: " + status);
        });
    });
});

$.post() Method

The $.POST sends a HTTP Post request and gets response back from the server. The following snippet of jQuery code sends a POST request and appends the result to the div myDiv.

    $("#btn").click(function() {
      $.post("post_data.php", {dataToPost: "myData"},function(result){
        $("#myDiv").html(result);
      });
    });

Optionally, we can also specify dataType when sending a POST request. The dataType indicates the type of the data expected from the server response. jQuery will do a guess if we do not specify the dataType. The possible types are html, xml, JSON and text etc.

I hope this article would have provided the very basis idea on using the jQuery Ajax in your project. In my next posts I will write about various examples using the jQuery Ajax. If you want to receive the mail updates, please subscribe here.

also read:

  • Introduction to jQuery
  • jQuery Selectors : ID selector, Class selector and Element selector

If you are looking for a good book on jQuery, please buy jQuery in Action

Category: jQueryTag: jQuery

About Ganesh Prakhya

Previous Post: « Book Review : SCJP Sun Certified Programmer for Java 6 Study Exam 310-065 Guide
Next Post: Android Application Development Tutorials »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact