Sunday, May 9, 2010

Ajax Shorthand in JQuery

 Welcome again to JQuery Coder and this time I will be teaching you how to setup ajax in JQuery.

One of the most commonly used technologies nowadays is AJAX. Most of the websites around the world are using AJAX as the foundation of processing information from the client to the server and back to the client. By the way, AJAX stands for Asynchronous Javascript and XML. During the time JQuery is not around, we uses the javascript to create the process of AJAX using HTTP Object. But, as JQuery arrive in the internet and being used by most of the programmer nowadays. AJAX is now easy to implement and manipulate. Let’s take a look some example that I’m going to create in order to have AJAX in our web pages.

First, we need to know the basic concept of AJAX. AJAX is the process of requesting information from the server and transfers it using XML but we can use also script or text for transferring information. We need also to know the basic part of the AJAX.

  1. Type – it will be the type of request that it will used during form submission (like POST or GET).
  2. url – it will be the url path in which where the server script reside.
  3. data – it will be the data to be submitted in the server for request.
  4. dataType – This will be what type of data should be transfer once it will be requested.

The next one will be the state of the AJAX and these are the common state:
  1. beforeSend – you can anything here while the AJAX is going to send the data.
  2. success – the AJAX is already done the process and sent back the information to the client.

For our first example, we are going to use text dataType:

Php files – We need this server side script for the request.


echo “Hello World!” . $_POST[‘name’];

HTML Tags


        
        


JQuery Script

$(document).ready(function(){
            $(‘#btnSubmit’).live(“click”, function(){
                        $.ajax({
                                    Type: “POST”,
                                    url: [path of the php file],
                                    data: “name=”+$(‘#txtName’).attr(“value”)+””,
                                    dataType: “text”,
                                    beforeSend: function(){
                                                alert(“Loading….”);
},
Success: function(data){
            Alert(data);
}
});
});
});

This is the sample code of the AJAX using JQuery and the data inside the function (which can be found in the success). Is where the information will be sent from the server-side script. In order to send you need to use echo or print to send data in the javascript using AJAX.

The next tutorial will be using XML as the data to be sent to the client.

No comments: