Galin Iliev's blog

Software Architecture & Development

How to insert record to DB using Javascript and Astoria Service

I wrote several posts regarding Astoria Services and in this one I will demonstrate how to insert reocord in database using AJAX calls.

Read my previous post - How to consume Astoria Service - in order to get deeper into solution environment.

I extended Javascript code so there is one more function that add new record to database. As it is for demostration purposes excuse hard-coded values, please.

So in order to add new record you need:

  • to create and instanciate variable with appropriate JSON format. Be careful here! All required fields from DB must present and have valid values.
  • set HTTP POST verb to the request.
  • set URL that point to root of entity type (Customer in our case)
  • set Request's headers "Accept" AND "Content-Type" to "application/json"
    wRequest.get_headers()["Accept"] = "application/json";
    wRequest.get_headers()["Content-Type"] = "application/json";
  • set request body's content with serialized variable content.

and finally call Invoke() method.

Here is full function:

   1:  function createNewCustomer(custID, contactName, companyName)
   2:  {
   3:      //create new item
   4:      var customer = {__metadata: {Type:"Customer" },
   5:          CustomerID:custID ,ContactName: contactName, CompanyName: companyName, ContactTitle:"", Address:"", City:""
   6:          , Region:"", PostalCode:"", Country:"", Phone:"", Fax:"" };
   8:      //save item to server using Astoria Service
   9:      var wRequest =  new Sys.Net.WebRequest();
  10:      wRequest.set_httpVerb("POST");
  11:      wRequest.set_url("http://galcho-pc:86/northwind.svc/Customers"); 
  13:      wRequest.get_headers()["Accept"] = "application/json";
  14:      wRequest.get_headers()["Content-Type"] = "application/json";
  15:      wRequest.add_completed(function (response, eventArgs){
  16:          var statusText = response.get_statusText();
  17:          alert(statusText);
  18:      });
  20:      wRequest.set_body(Sys.Serialization.JavaScriptSerializer.serialize(customer));
  21:      wRequest.invoke();
  22:  }

And the button that execute is defined with following HTML

<input type="button" value="New Customers" onclick="createNewCustomer('AAAA','Galin Iliev', 'Galcho.COM');" />

Hope you find it interesting.

UPDATE: Here is sample project: (191.09 KB)

In order to run sample project do following:

  • make sure you installed the packages stated here.
  • extract files and modify Connection string NorthingEntites in web.config to match your SQL server that run Northwind DB
  • when running the sample make sure the URL in browser's address bar contain same hostname as in astoriaUrl JS variable (Default.aspx line 29) otherwise you will get "Access Denied!" error from browser single origin restriction.