Using jQUery .load(), ajax wrapper method

In the Posting data to REST service in PhoneGap/Cordova i talked about how to use jQuery to make a HTTP POST call to a REST service. In that case i used $.post() method, But jQuery also provides one wrapper method load() that makes making AJAX call even simpler. I wanted to try that so i changed the sample to use the load(). The load() method works on jQuery selector, so it first makes AJAX request and then takes the response of AJAX method and inserts it in all the elements returns by the selector. In my case first i did create a HTTP form and when i click on it, i want to collect all the values entered by the user on the form and use them to make HTTP POST call and once the result it returned i want to insert it into html div with id equal to result. This single line of code does everything $('div#result').load('', $("#insertContact :input")); First i am selecting a div with id equal to result by using $('div#result') selector, the parameter is the URL to which the XHR request should be made. Second paramater $("#insertContact :input") says that select the form insertContact and return all the inputs on it in array format and submit them to the URL.

<!DOCTYPE html>
<title>Manage Contact</title>
<script src=""></script>
<script type="text/javascript" charset="utf-8">
    function insertContact(){
      console.log("Entering insertContact()");
   $("#insertContact :input")); 
      return false;
  <form id="insertContact">
        <td>Contact Id</td>
        <td><input type="text" name="contactId" /></td>
        <td>First Name</td>
        <td><input type="text" name="firstName" /></td>
        <td>Last Name</td>
        <td><input type="text" name="lastName" /></td>
        <td><input type="text" name="email" /></td>
        <td><input type="submit" id="submit" name="submit" 
  value="Submit" /></td>
  <div id='result'></div>
The load() method looks at the second parameter to figure out if the request should be made using HTTP GET or POST. If i wanted to submit the form using HTTP GET i should have used $('div#result').load('', $("#insertContact").serialize());

No comments: