CRUD Operation in HTML/JavaScript Using Windows Azure Mobile Service

This article helps you to understand CRUD operations in HTML/JavaScript applications using mobile services. Before reading this article I recommend you first read my previous article that helps to become familiar with Quick Startup projects in HTML/JavaScript applications and it also helps you to setup your mobile service as a backend for your HTML/JavaScript website. Click here to read my previous article.

I have created a simple demo application to understand the CRUD operation. The attached project is capable of inserting, updating, reading and deleting data in mobile services. You can download it from this article (at the end of this article you will find steps for setting up my attached project in the Windows Azure Portal).

As we know the Windows Azure Mobile Service is a cloud based backend service so whatever operation we do, we need a Mobile Service URL and Mobile Service Key. The Mobile Service URL and Mobile Service Key are automatically created during creation of the Mobile Service. We can find them in the Quick Startup project.

Let's start CRUD Operation

1. Add Mobile Service SDK to your project

You can get the mobile service SDK from the Windows Azure portal but in the HTML/JavaScript platform you can get it from the Quick Startup project or you can browse the following URL http://your_mobile_url/client/MobileServices.Web-1.0.0.min.js

Get your free Mobile Service SDK and add it in your HTML/JavaScript project. As shown in the following image.

CrudOperation1.jpg

2. Initialized MobileServiceClient class instance

Before we start to do CRUD Operations, we need to initialize the MobileServiceClient Class with the mobile service URL and mobile service key.

var client = new WindowsAzure.MobileServiceClient("{Your mobile service URL}", "{Your mobile service key}");

3. Insert Operation

var item = { Name: "Naren Chejara", Age: 27, CreatedAt: new Date() };
var table = client.getTable("{Table name}");
    table.insert(item).done(function (insertedItem) {
        alert("'"+ insertedItem.Name + "' is inserted into in " + tableName +" table.");
    },
    function (error) {
        alert("Error Occur during Insert" + JSON.stringify(error));
    });

In the code above, we are trying to do the following:

  1. Create an Item array for table. Item array used in insert method to insert data into table.
  2. Get the table name by using client.getTable("{Table name}") method. This method can verify the name that we as method parameter. If there is not such table name available in the mobile service then client SDK throw the exception.
  3. Call insert method by ing item array as a parameters and then call done function. We can on success function and on error function as the parameter of done() function. On success function fire if insert method add item successfully in the table otherwise on Error function fired.
     
  4. Update Operation
     

    var table = client.getTable("{Table name}");
    table.where
    ({ Name: "Naren Chejara" }).read().done(

    function (results) {
       if (results[0].Name !== null) {
          table.update
    ({ id: results[0].id, Name: "Naren", Age: results[0].Age, CreatedAt: results[0].CreatedAt }).done(

            function (updatedItem) {
                alert
    ("'" + updatedItem.Name + "' is updated into in " + tableName + " table.");
           
    },
           
    function (error) {
                alert
    ("Error Occur during update .." + JSON.stringify(error));
           
    });
      }
     
    else {
         alert
    ("Now match found! Please click on the insert button and try again!");
     
    }

        },
       
    function (error) {
           alert
    ("Error Occur during Reading data for updation .." + JSON.stringify(error));
       
    });

    In the code above, our intention is to read the data from the table where the name equals "Naren Chejara" and store that data into in an array variable and do the update operation based on the id column. The id column is an auto increment column in the table; the user can only use the id column for a query. The Mobile service cannot allow the user to do an insert and update operation on the id column. The code above reads the data based on the where query and stores it in the results array. If the where query succeeds then the code above updates the specific column.
     

  5. Delete Operation
     

    var table = client.getTable("{Table name}");

    table.where({ Name: "Naren" }).read().done(

          function (results) {
             
    if (results[0].Name !== null) {
                   table.del
    ({ id: results[0].id}).done(

                      function (updatedItem) {
                        alert
    ("Id = " + results[0].id + " is deleted from " + tableName + " table.");
                     
    },
                     
    function (error) {
                        alert
    ("Error Occur during update .." + JSON.stringify(error));
                     
    });
             
    }
             
    else {
                    alert
    ("Now match found! Please click on the insert button and try again!");
             
    }
         
    },
         
    function (error) {
             alert
    ("Error Occur during Reading data for deletion .." + JSON.stringify(error));
         
    });

     

  6. Read Operation
     

    var table = client.getTable("{Table name}");

    table.read().done(

       function (results) {
           
    if (results.length > 0) {
                alert
    ("Total " + results.length + " records are in '" + tableName + "' table");
           
    }
           
    else{
                alert
    ("'" + tableName + "' table is empty ..."); 
           
    }
      
    },
      
    function (error){
            alert
    ("Error Occur during Reading data .." + JSON.stringify(error));
      
    });

     

The Mobile Service SDK also contains many other methods that help us in CRUD Operations. The following are some methods that we can use during CRUD operations.

  1. select() method : This method reads specific columns from the table.

    Usage

    client.getTable("table name").where({ Name: "Naren Chejara" }).select("id", "Name").read().done();
    client.getTable("table name").select("id", "Name").read().done();
     
  2. orderBy() method: This method sorts a table column in ascending and descending order.

    Usage

    Ascending order:

    client.getTable("table name").where({ Name: "Naren Chejara" }).orderBy("id").read().done()
    client.getTable("table name").orderBy("id").read().done()

    Descending order:

    client.getTable("table name").where({ Name: "Naren Chejara" }).orderByDescending("id").read().done()
    client.getTable("table name").orderByDescending("id").read().done()
     
  3. take() method: This method reads specific top results.

    Usage

    client.getTable("table name").where({ Name: "Naren Chejara" }).take(2).read().done()
    client.getTable("table name").take(2).read().done()
     
  4. skip() method: This method skips specified records and reads other data.

    Usage

    client.getTable("table name").where({ Name: "Naren Chejara" }).skip(2).take(2).read().done()
    client.getTable("table name").skip(2).take(2).read().done()
     
  5. where() method allow us to filter our data like we did in SQL.

    Usage

    client.getTable("table name").where({ Name: "Naren Chejara", Age:20 }).read().done()
    client.getTable("table name").where(function (){ return this.id > 5 }).read().done()
    Above query return 50 result. All result are > 5. this keyword contains table schema so you can use this keyword like this.id or this.Name
     
  6. odata query: Mobile Service SDK can also support the odata query format.

    Usage

    client.getTable("table name").read("$filter=(id gt 10").done()

How to set up attached application (or your own application) in Windows Azure Portal.

  1. Download the attached project from this article.
  2. Create a new website in the Windows Azure portal and deploy the downloaded project to your website
  3. Create a new mobile service in Windows Azure and create a Person table (My project uses the person table inside the code)
  4. Configure your mobile service with your website host name:

    1. Open the configure tab in your mobile service
    2. Add your website Host name in the Cross-Origin resource sharing (cors) and click on the save button.
     
  5. Open your website URL in any browser
  6. If you have deployed the attached project properly in your website then the browser will show the following page:

    CrudOperation2.jpg

Add your mobile service URL and mobile service key and use this application in sequence (insert, update, delete and read).

I hope that this article will help you to understand CRUD operations in HTML/JavaScript applications using Mobile Service. Thanks for reading


Similar Articles