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('http://192.168.1.101:9000/ManageContact/rest/contact', $("#insertContact :input")); First i am selecting a div with id equal to result by using $('div#result') selector, the http://192.168.1.101:9000/ManageContact/rest/contact 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>
<html>
<head>
<title>Manage Contact</title>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript" charset="utf-8">
  $(document).ready(function(){
    $("#submit").click(insertContact);
    function insertContact(){
      console.log("Entering insertContact()");
      $('div#result').load('http://192.168.1.101:9000/ManageContact/rest/contact',
   $("#insertContact :input")); 
      return false;
    }
  });
</script>
</head>
<body>
  <form id="insertContact">
    <table>
      <tr>
        <td>Contact Id</td>
        <td><input type="text" name="contactId" /></td>
      </tr>
      <tr>
        <td>First Name</td>
        <td><input type="text" name="firstName" /></td>
      </tr>
      <tr>
        <td>Last Name</td>
        <td><input type="text" name="lastName" /></td>
      </tr>
      <tr>
        <td>Email</td>
        <td><input type="text" name="email" /></td>
      </tr>
      <tr>
        <td><input type="submit" id="submit" name="submit" 
  value="Submit" /></td>
      </tr>
    </table>
  </form>
  
  <div id='result'></div>
 
</body>
</html>
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('http://192.168.1.101:9000/ManageContact/rest/contact', $("#insertContact").serialize());

No comments: