Introducing the jQuery CRUD extension

I’ve been getting my hands dirty with some jQuery/JavaScript, WCF, JSON, and REST lately doing a back-end domain layer exposed via WCF as RESTful service operations that communicate via JSON.

On the client I’ve used jQuery as means for communicating with the WCF endpoints to get data and create/update/delete data…aka CRUD.

What I’ve come to learn is that it’s sometimes very cumbersome and time-consuming to create these $.ajax(…{}) calls via jQuery, specifying a bunch of settings every time, so I decided to create a plugin/extension that would make things easier for me when I communicated with these RESTful operations.

For the purpose of demonstrating this extension I’m going to use a small scenario and throughout it explain what the extension does.


The code

The code can be found @GitHub or downloaded via NuGet (Install-Package jQuery.CRUD).


The services

For this purpose of this post I’ve created a tiny domain consisting of books and authors. Consequently I have two endpoints, books and authors with these available operations:

Book Service Operations

image

  • Read Operations (3): all books OR all books within a genre OR one book with a specified id
  • Create Operations (1):create a new book
  • Update Operations (1):update a book with a specified id
  • Delete Operations (1): delete a book with a specified id

Author Service Operations

image

  • Read Operations (2): all authors OR all books by one author with a specified id

These endpoints are exposed via WCF via routes but since this post’s topic isn’t about WCF we’ll leave the services now knowing that they respond via JSON and subsequently expect JSON input when using PUT or POST.

The client

As I previously stated when using jQuery for communicating with a service that exposes RESTful endpoints it’s sometimes a bit cumbersome to work with jQuery’s $.ajax function. On the contrary, the $.getJSON is a bit to simple for me sometimes so what I did was to look around the web for what was available when working with REST and JSON with jQuery.
I found this plugin by Nathan Bubna but somehow I didn’t get it to work and there wasn’t any samples included. But I took Nathan’s excellent code and decided to change some things and add some other things.

The jQuery extension

Disclaimer: I’ve created this extension for the purpose of using it myself, hence it works like I want it to. I may not suit all needs for every application. But, feel free to change the code anyway you like it…

  • $.Create(uri, data, callback, options) – POST
  • $.Read(uri, data, callback, options) – GET
  • $.Update(uri, data, callback, options) – PUT
  • $.Delete(uri, data, callback, options) – DELETE

Those are the methods that this extension/plugin adds to jQuery. They are added to jQuery/$ itself and therefore will not work together with the $() selectors. Again…that’s what I wanted, easy enough to change if you’d like that.

image

Each of the methods take at most four parameters; URI, DATA, CALLBACK, and OPTIONS

  • URI: the uri/url to the RESTful operation. e.g. “books”. Can also be used with placeholders such as
    “books/{id}”. This parameter is required
  • DATA: optional data to send. If data contains an object like {id:1} then the id placeholder in the uri will be replaced (i.e. “books/1”). If it’s a create or update call (i.e. POST/PUT) the data: {JSON obj}within object will be JSON serialized ( e.g. {data: {Id:1, Title: “The title”}} ), after the replacement has taken place (which removes all the replacement parameters from the data parameter), and sent as JSONto the service endpoint.The data parameter can also be replaced by the callback function (if there is no data to send), e.g.
    $.Read(“books”, OnSuccess).
  • CALLBACK: optional callback function to execute with the response (i.e. the success function of jQuery’s $.ajax method).The callback parameter can also be replaced by the options object, e.g.
    $.Read(“books”, OnSuccess, {cache:true, error: OnError}).
  • OPTIONS: optional options object that corresponds to jQuery’s $.ajax settings object. Use this to change any default settings or add something that wasn’t added by the extension.

Each of the methods call an internal function called execute and passes in the result from another internal function called prepare.
Prepare, in turn, is called via apply which is just a fancy way of calling a function when you don’t know the exact number of parameters you’ll pass…and yes, the first parameter is the this pointer (which we’ll come back to in a bit).

Let’s have a look at execute and prepare next:

image

Execute doesn’t need that much explaining, it simple calls the underling $.ajax method with the options that prepare will do for us. So prepare then:

image

I’m just showing parts of the prepare function that I find interesting to highlight. For instance, the first thing that happens is that I merge the default settings with the settings for the current operation. These look like:

image

Here’s where the THIS pointer comes into play. Since I call operations[this], this will be one of the values of $create, $read, $update, or $delete depending on which method was called. So what I’ll get is a combination of the default settings combined with the settings for the current operation. All of which can be altered by using the options parameter.

Prepare will then go on and parse, merge, replace etc the parameters that was sent to it…have a look in the code if you’re interested.

So, now that you know how the extension works…let’s take it out for a spin.

Note: the OnSuccess method used in the following examples looks like this

function OnSuccess(response) {
// do stuff with response which is a
JSON object
}

READ: all books

$.Read(“books”, OnSuccess);

returns:

image

READ: book by id

$.Read(“books/{id}”, { id: “bk101” }, OnSuccess);

returns:

image

READ: books in a specific genre

$.Read(“books?genre={genre}”, { genre:”Romance” }, OnSuccess);

returns:

image

CREATE: book

var book = {
Id: “bk113”,
Title: “The new book”,
Genre: “NewAge”,
Description: “This is the newest book on the shelf”
};
$.Create(“books”, book, OnSuccess);

returns:

image

UPDATE: book

var book = {
Id: “bk113”,
Title: “The new book”,
Genre: “Romance”,
Description: “This is the newest book on the shelf”
};
$.Update(“books/{id}”, {id: “bk113”, data: book}, OnSuccess);

returns:

image

DELETE: book

$.Delete(“books/{id}”, { id: “bk113” });

READ: books by an author

$.Read(“authors/{author}/books”, { author: “Corets, Eva” }, OnSuccess);

returns:

image

, , ,

  1. #1 by Martin John Bramwell on July 2, 2014 - 20:58

    You’d help me enormously if you’d provide a short HTML snippet that actually calls one of the functions correctly. In my newbie attempts, I tried ” $.Read(“books”, OnSuccess); “, and got an immediate, “Uncaught SyntaxError: Unexpected token ILLEGAL”

Leave a comment