Javascript HTTP Request Tutorial Using JQuery

In our previous post, we discussed the basics of triggering a HTTP request through Javascript using the XMLHttpRequest object. In this short tutorial, we will discuss how to invoke a HTTP request through JQuery framework . To get started with this, you will have to include the JQuery library into your HEAD section of the HTML page, by using the code snippet given below.
  <head>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
  </head>
You will really appreciate the power of JQuery, as it makes the coding much easier. This will be evident from the subsequent steps that we will be using to access a different page. (This example is for HTTP GET request only, a POST example will be provided shortly). We will create a sample HTML page, that will be loaded from the main HTML page. (call it, samplepage.html). The content of the example page is provided below
<html>
<body>
Invoked via GET Request, JQuery
</body>
</html>  
We have the test page ready, have loaded the JQuery library; The code to invoke the HTTP GET request is provided below
  <html>
  <head>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
  </head>
    <body>
      <div id="result"></div>
    <script>
    $.get('samplepage.html', function(data) {
                    $('#result').html(data);
                    alert('A Javascript HTTP Request was Triggered using JQuery');
    });
    </script>
    </body>
  </html>  
Wow, look at the code reduction when done through JQuery.You can test this example by yourself. When you load the test page, it will invoke a GET request and load the data into the main page in the div "result". Note that we are referencing the div using "#result" in the JQuery code snippet. This looks a lot cleaner than the original XMLHttpRequest example. If you are writing a widget in Javascript, that already uses the JQuery library, then you can afford to use this method to trigger a GET request if required. But, it is not possible to create cross domain HTTP requests using JQuery.(if you know, you can share it).

In the next post, we will discuss, how to create a HTTP request call using Prototype Javascript framework.

No comments:

Post a Comment