Pushing Content with Data Requests

When making data requests, you may sometimes need to push content to the server to which you are connecting—for example, if you are pushing new user configuration settings to your server in order to update the database record for the user:

<label for="user"></label>
<input type="text" name="user" id="user" /><br />
<label for="pass"></label>
<input type="hidden" name="pass" id="pass" />
<button onclick="updateRecord();">Update User</button>
<div id="response"></div>

<script type="text/javascript">
function updateRecord(){
   //set up url and post data
   var url = "http://www.mysite.com/updateUser.php";
   var postData = "user=" +
      encodeURIComponent(document.getElementById("user").value) + "&pass=" +
      encodeURIComponent(document.getElementById("pass").value);

   //POST data object to URL
   osapi.http.post({
      "href": url,
      "body": postData,
      "format": "text"
   }).execute(function(response){
      document.getElementById("response").innerHTML = "Data Posted";
   });
}
</script>

In our POST request, we set up the markup to allow a user to input her username and password. These values represent the information that we will pass to the server to update the user record. We also set up a div to display a confirmation that the message was sent. When the user clicks the button, the updateRecord() function will be executed.

In the ...

Get Programming Social Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.