zimki | documentation | search
 
Zimki Documentation - CookBook.WebService.Client2

Now we want to build on the web service client to allow us to add quotes to the database using AJAX calls.

Open up the Service JavaScript instance and add the following code to it:

function addQuote(name, price, quantity) {
  Quote.create({
    name: name,
    quantity: quantity,
    price: price
  });
}
zimki.publishService( 'addQuote', addQuote, '');

This adds a service call we can use to add more quotes to the database. We then need a form to input the quotes, and a way to make that call send a request to the service to add the new quote. Replace the quotes template with this:

<html>  
<head>   
  <title>My AJAX quote service</title>

  <!-- import the zimki client-side library -->
  <script language="JavaScript" src="http://service.zimki.com/u/js/zimki.js"></script>
  <script type="text/JavaScript">

  zimki = new zimkiClient('${zimki.apikey}');

  function GetQuote() {
    zimki.call('myQuotes', {}, UpdateQuotes);
  }

  function UpdateQuotes(data) {
    var table = '<table><tr><th>Item</th><th>Quantity</th><th>Price</th></tr>';
    for (var i = 0; i < data.stock.length; i++) {
      var p = data.stock[i];
      table += "<tr>";
      table += "<td>" + p.name + "</td>";
      table += "<td>" + p.quantity + "</td>";
      table += "<td>" + p.price + "</td>";
      table += "</tr>";
    }
    table += "</table>";

    document.getElementById('QuoteArea').innerHTML = table;
  }

  function NewQuote() {
    zimki.call('addQuote', {
      name: $('name').value,
      quantity: $('stock').value,
      price: $('price').value
    });
    GetQuote();
  }
  </script>
</head>

<body>
  <p>The time is: ${time}</p>
  <p>Add a quote: </p>
  <table><tr><th>Item</th><th>Quantity</th><th>Price</th></tr>
  <tr>
  <td><input type="text" id="name" value="" /></td>
  <td><input type="text" id="price" value="" /></td>
  <td><input type="text" id="stock" value="" /></td>
  </tr>
  </table>
  <input type="submit" value="Add and Get Quotes" onclick="NewQuote()" 

  <form>
    <input type="button" value="Get all quotes" onClick="GetQuote()"/>
  </form>
  <div id="QuoteArea" />
</body>
</html>

Now visit the root of your realm. You now have a realm with a form that allows you to add entries to your quote database with AJAX calls, and also reads in a list of all the current quotes using an AJAX call.

Next step

  1. In the addQuote service call, validate the incoming request and throw apropriate errors if arguments are missing or of the wrong type
  2. Avoid adding new quotes if we're already seen the name before; in that case, the details of that quote should be updated instead

See also

Parent

CookBook.WebService