HowTo:Use AJAX and REST in a Web Page to POST data

From AgileApps Support Wiki

For:   Designers
Level: Advanced
Time: 15 minutes

See more:
    ◾ HowTo Guides

This example adds a new entry to the ultra-simple Customers object in the Sample Order Processing System. To keep the example as simple as possible, the data is hard-wired into the script.

Considerations
  • In this case, we'll use a synchronous request, because we don't want the rest of the page to render until after the attempted POST has completed.
  • A unique key has been defined for the Customer object, so only the first POST should succeed. Subsequent POSTs should fail.
  • POST requests return 201 when successful (unlike other REST requests, which return 200).
<syntaxhighlight lang="javascript" enclose="div">

<html> <head> <script type="text/javascript"> function createNewCustomer() {

   // Create the communications object.
   var xmlhttp;
   if (window.XMLHttpRequest) {
       // code for IE7+, Firefox, Chrome, Opera, Safari
       xmlhttp=new XMLHttpRequest();
   }
   else {
       // code for IE6, IE5
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   
   // Set up the request to send XML data to the server.
   // Make it synchronous, so we know how page rendering should proceed
   async = false;
   resource = "/networking/rest/record/customer?alt=json";
   data = 
     "<platform>                                      \
         <record>                                     \
             <customer_name>Ian</customer_name>       \
             <company_address>SoHo</company_address>  \
         </record>                                    \
     </platform>";
   
   xmlhttp.open("POST", resource, async);    
   xmlhttp.setRequestHeader("Content-type", "application/xml"); 
                                      // or "application/json"
   xmlhttp.send(data); 
   
   var text = "";

//text = "

" + xmlhttp.responseText + "

"; //For debugging

   // Echo the return value.  Success = 201
   var reply = eval('(' + xmlhttp.responseText + ')');
   if (xmlhttp.readyState==4) {
     if (xmlhttp.status==201) {
       text += "Customer added successfully.
"; text += "Record ID: " + reply.platform.message.id; } else { text += "Customer add failed.
"; text += "HTTP Status = " + xmlhttp.status + "
"; text += "Platform Status = " + reply.platform.message.code + "
"; text += reply.platform.message.description; } } document.getElementById("myDiv").innerHTML=text;

} </script> </head>

<body>

Click the button to create a new customer.

   <button type="button" onclick="createNewCustomer()">Ok</button>

</body>

</html> </syntaxhighlight>

The result of a successful POST looks like this:

<syntaxhighlight lang="javascript" enclose="div">

Customer added successfully. Record ID: 313913951 </syntaxhighlight>

Learn more: AJAX and REST: POST/PUT Syntax