JavaScript - JSON and REST

From XennisWiki
Jump to: navigation, search

This article shows a JavaScript example of how to post and get data via a REST API using JSON.

Example

Sample API

js/sampleapi/HttpClient.js

<gist file="HttpClient.js">9263633</gist>

js/sampleapi/sampleAPI.js

var SampleAPI = function() {

  var API_URL = "http://localhost:8000/api/v1/";

  var access_token = "f0d56e5";

  var client = new HttpClient();


  this.postLocation = function(location) {
    client.httpPost(API_URL + "location/", "OAuth " + access_token, location,
      function (jqXHR, textStatus) {
        console.log("receive: created");
        $("#postResult").text(textStatus + " " + jqXHR.status + " " + jqXHR.statusText);
      },
      function (jqXHR, textStatus) {
        var completeMessage = textStatus + " " + jqXHR.status + " " + jqXHR.statusText;
        console.log("receive: " + completeMessage);
        console.log(jqXHR.responseText);
        $("#postResult").text(completeMessage);
      }
    );
  }


  this.getLocations = function() {
    client.httpGet(API_URL + "location/", "OAuth " + access_token,
      function (data, textStatus, jqXHR) {
        var completeMessage = textStatus + " " + jqXHR.status + " " + jqXHR.statusText;
        console.log("receive: " + completeMessage);
        $("#getResult").text(completeMessage);

        $.each( data.objects, function( i, item ) {
          $("#locations").append("<li>" + item.latitude + ", " + item.longitude + ": " + item.altitude + "</li>");
        });
      },
      function (jqXHR, textStatus) {
        var completeMessage = textStatus + " " + jqXHR.status + " " + jqXHR.statusText;
        console.log("receive: " + completeMessage);
        $("#getResult").text(completeMessage);        
      }
    );
  }
}

js/main.js

$(document).ready(function() {

  var sampleAPI = new SampleAPI();

  // ------------------------ get locations ------------------------
  $("#getLocations").click(function() {
      getLocations(API_URL);
  });

  // ------------------------ post location ------------------------

  // Attach a submit handler to the form
  $("#postLocation").submit(function( event ) {
    // Stop form from submitting normally
    event.preventDefault();   

    // Get some values from elements on the page:
    var $form = $( this ),
      url = $form.attr( "action" );
   
    var data = JSON.stringify({
        user_id: 3,
        latitude: $form.find( "input[name='latitude']" ).val(),
        longitude: $form.find( "input[name='longitude']" ).val(),
        altitude: $form.find( "input[name='altitude']" ).val(),
    });
    postLocation(url, data);
  });

});

User interface

<!doctype html>
<html lang="en">

<head>

  <meta charset="utf-8">

  <title>HTML/JS Client</title>

  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="js/sampleAPI.js"></script>
  <script src="js/main.js"></script>

</head>

<body>

	<h3>Post location</h3>

	<form action="http://localhost:8000/api/v1/location/" id="postLocation">
	  <input type="number" name="latitude" placeholder="Latitude">
	  <input type="number" name="longitude" placeholder="Longitude">
	  <input type="number" name="altitude" placeholder="Altitude">
	  <input type="submit" value="Post location">
	</form>

	<p>Result: <span id="postResult"></div></p>

	<hr>

	<h3>Get locations</h3>

	<button type="button" id="getLocations">Get locations</button>
	<p>Result: <span id="getResult"></div></p>

	<ul id="locations"></ul>

</body>

</html>

See also