Git Product home page Git Product logo

jquery.rest's Introduction

jQuery.rest

A plugin to ease AJAX interaction with RESTful APIs such as Rails

Accepted Parameters

There are four public jQuery methods created by this plugin:

jQuery.create
jQuery.read
jQuery.update
jQuery.destroy

Each function accepts 1-4 parameters:

url [, data [, success [, error ] ] ]
  • url: (string) The url of the resource, which can include a dynamically populated value surrounded by {braces}
  • data: (hash | string) The data to post to the resource, also used to populate dynamic values.
    • In GET requests, data will be added to the url as query-string parameters
  • success: (function) The success callback
  • error: (function) The error callback

In addition to these parameters, you can simply pass a standard jQuery.Ajax options object instead as the only parameter.

Breaking change: success, error callback parameters

Both success and error callbacks are passed a headers object whose key-value pairs correspond to the HTTP Response headers.

  • success
    • data: The reponse data for the request
    • headers
    • xhr
  • error
    • xhr
    • headers

In addition to being passed to the callbacks, this parsed object is attached directly to the xhr as well.

var xhr = $.read('/tasks.json');
xhr.responseHeaders
// => Object {
// =>   Connection: "close",
// =>   Content-Length: "543",
// =>   Content-Type: "application/json;charset=utf-8"
// => }

This was inspired by the [GitHub][gh] API which makes use of custom HTTP response headers and the fact that xhr.getAllReponseHeaders() is next to useless. [gh]: http://developer.github.com/

Example

Create a new 'task' record with a success callback

$.create(
  '/tasks',
  { description: 'follow up after meeting' },
  function (reponse) {
    alert('successfully added task.');
  }
);
// => [POST] /tasks
// => authenticity_token: K06+3rRMlMuSoG60+Uw6UIo6UsZBbtIIPu2GaMbjf9s=
// => description: follow up after meeting

Read an existing 'account' object and add it to the page (this callback is making some assumptions about your controller -- YMMV)

$.read(
  '/accounts/2486',
  function (response) {
    $('ul#accounts').append(response);
  }
);
// => [GET] /accounts/2486

Update an existing 'task' record with ID 54

$.update(
  '/tasks/54',
  { description: 'lunch tomorrow after 1pm' }
);
// => [PUT] /tasks/54
// => authenticity_token: K06+3rRMlMuSoG60+Uw6UIo6UsZBbtIIPu2GaMbjf9s=
// => description: lunch tomorrow after 1pm

Update a nested 'task' record using dynamic IDs

$.update(
  '/accounts/{account_id}/tasks/{id}',
  { id: 54, account_id: 11387, description: 'lunch tomorrow after 1pm' }
);
// => [PUT] /accounts/11387/tasks/54
// => authenticity_token: K06+3rRMlMuSoG60+Uw6UIo6UsZBbtIIPu2GaMbjf9s=
// => description: lunch tomorrow after 1pm

Delete a 'task' object with ID 54

$.destroy('/tasks/54')
// => [DELETE] /tasks/54

Delete a 'task' object using alternate syntax

$.destroy({
  url: '/tasks/54',
  success: function (response) {
    alert('successfully deleted task.');
  }
});
// => [DELETE] /tasks/54

Using $.Deferred

jQuery.rest helpers all support the new jQuery.Deferred syntax:

$.read('/tasks/{id}.json', { id: 34 }).then(function (task) { /* do something with task */ });

Setting Content-Type header

jQuery.rest will look for a content-type setting in three places:

  1. options.contentType if you're using the alternate syntax
  2. or else $.restSetup.contentType
  3. or else it will look for a json or xml extension on the url resource.

If all three of those sources fail, it will use the browser's default.

Setting csrf token & method parameter

There is a global object called $.restSetup that you can modify in your application's Javascript startup to match your environment.

$.restSetup.csrfParam and $.restSetup.csrfToken define how the authenticity token is formatted. By default they are loaded from meta tags named csrf-param and csrf-token. Set them manually if you are unable to follow this convention.

PUT and DELETE verbs are used by default, but if you need to tunnel them through the POST method instead: $.restSetup.useMethodOverride = true;

$.restSetup.methodParam can be changed if you pass back the REST method differently. Defaults to _method.

Example:

$.extend($.restSetup, {
  useMethodOverride: true,
  methodParam: 'action',
  csrfParam: '_csrf',
  csrfToken: encodeURIComponent(AUTH_TOKEN)
});

-- or --

<meta name="csrf-param" content="_csrf" />
<meta name="csrf-token" content="K06+3rRMlMuSoG60+Uw6UIo6UsZBbtIIPu2GaMbjf9s=" />
$.destroy('/tasks/54');
// => [POST] /tasks/54
// => action: delete
// => _csrf: K06+3rRMlMuSoG60+Uw6UIo6UsZBbtIIPu2GaMbjf9s=

Customize HTTP verbs

By default, jQuery.rest conforms to Rails' HTTP verbs: POST to create, PUT to update, DELETE to destroy.

Not all RESTful APIs behave this way, and some argue that this isn't actually REST. If you need to override the methods being used, you can customize $.restSetup.verbs.

$.restSetup.verbs.update = 'PATCH';
$.update(
  '/accounts/{account_id}/tasks/{id}',
  { id: 54, account_id: 11387, description: 'lunch tomorrow after 1pm' }
);
// => [PATCH] /accounts/11387/tasks/54
// => authenticity_token: K06+3rRMlMuSoG60+Uw6UIo6UsZBbtIIPu2GaMbjf9s=
// => description: lunch tomorrow after 1pm

($.read will of course always use GET, but the others can be changed to anything you desire.)

jquery.rest's People

Contributors

alassek avatar asan avatar fliptheweb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

jquery.rest's Issues

Using jquery.rest with inherited_resources

First, congratulations for writing a very useful plugin. I'm trying to use it in combination with inherited_resources, and although the "read" action works, "update" only returns an empty hash, even though I get a "success" 200 status code.

How should I configure my controller to get it to work? Right now all I have is this:

class Admin::DesignersController < Admin::BaseController

  respond_to :html, :json

end

(with BaseController inheriting from inherited_resources)

Content-Type management

Currently sending data as text/html. We should automatically set the content-type header when:

  • User defines $.restSetup.contentType
  • Url includes a resource ending in .json or .xml

Perhaps I should provide an API for setting headers.

Support JSON contentType

Some JSON APIs require sending application/json to the server instead of application/x-www-form-urlencoded.

Rework data-object and url-substitution code to support using JSON.stringify instead of jQuery.param.

Related to #12

Does not work with rails 3 jquery ujs driver

The rails 3 ujs driver defines a beforeSend function which is expecting a settings object so it can set correct accept headers. I'm seeing two problems with jquery.rest. First, on line 139 the apply method is being called on userBeforeSend, but apply requires an array as its second argument. I believe this should be:

if ( $.isFunction(userBeforeSend) ) userBeforeSend.call(context, xhr);

But even though that works, because the ujs driver is expecting a settings object you get a typeerror when that line runs. I'm not familiar enough with js or jquery to fix it myself. If you could point me in the right direction, I'd be happy to submit a pull request.

$.update does not send right Accept header

Hi,

i like principle of REST queries for jQuery, that is really great idea. But i don't know where is problem.

I write simple ordering with acts_as_list, jQuery sortable and jQuery.REST.

Have this action in categories controller:

  def update_position
    params[:category].each.with_index do |id, index|
      Category.update_all({position: index+1}, {id: id})
    end

    index
  end

After update i want to update positions in HTML table. so have this view:
update_position.js.erb

<%- @categories.each do |category| %>
  $('#' + '<%= dom_id(category) %>' + ' .position').html(<%= category.position %>);
<%- end %>

But when is JS event called with

$.update(
  $(this).data('update-url') + '.js', $(this).sortable('serialize')
);

it is returned like JSON (Accept header is application/json at first, second is text/javascript what i want), so my view isn't executed. But when i call event with normal post query:

$.post(
  $(this).data('update-url') + '.js', $(this).sortable('serialize');
);

it is executed.

read() requests caching in IE7

Hi,

I find that GET requests are caching for me in IE7 when I try a $read against a resource. As a workaround I have changed the read() function in the jquery.rest code to be:

 function read () {
   collect_options.apply(this, arguments);
   $.extend(options, { type: 'GET' })
   $.extend(options, { cache: false }) // STOP IE CACHING
   return $.ajax(options);
 }

However, is there a way I can pass this { cache: false } into the $read() method from my calling code - instead of modifying the code in into jquery.rest framework? I see you mention the following in the README:

"In addition to these parameters, you can simply pass a standard jQuery.Ajax options object instead as the only parameter"

However, I want to just supress caching.

Thanks again for publishing jquery.rest. I find it quite useful.

Regards,
Declan

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.