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.

  • 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).
<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>";"POST", resource, async);    
    xmlhttp.setRequestHeader("Content-type", "application/xml"); 
                                       // or "application/json"
    var text = "";
    //text = "<pre>" + xmlhttp.responseText + "</pre>";  //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.<br/>";
        text += "Record ID: " +;
      else {
        text += "Customer add failed.<br/>";
        text += "HTTP Status = " + xmlhttp.status + "<br/>"; 
        text += "Platform Status = " + reply.platform.message.code + "<br/>";
        text += reply.platform.message.description; 

    <div id="myDiv"><h2>Click the button to create a new customer.</h2></div>
    <button type="button" onclick="createNewCustomer()">Ok</button>


The result of a successful POST looks like this:

Customer added successfully.
Record ID: 313913951

Learn more: AJAX and REST: POST/PUT Syntax