Git Product home page Git Product logo

jquery.rest's Introduction

jQuery REST Client

v1.0.1

Summary

A jQuery plugin for easy consumption of RESTful APIs

Downloads

File Size Report

Original: 10314 bytes.
Minified: 5920 bytes.
Gzipped:  1376 bytes.

Features

  • Simple
  • Uses jQuery Deferred for Asynchonous chaining
  • Basic Auth Support
  • Helpful Error Messages
  • Memory Cache
  • Cross-domain Requests with XDomain

Basic Usage

  1. Create a client.
  2. Construct your API.
  3. Make requests.

First setup your page:

<!-- jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<!-- jQuery rest -->
<script src="http://jpillora.com/jquery.rest/dist/1/jquery.rest.min.js"></script>
<!-- WARNING: I advise not using this link, instead download and host this library on your own server as GitHub has download limits -->

<script>
  // Examples go here...
</script>

Hello jquery.rest

var client = new $.RestClient('/rest/api/');

client.add('foo');

client.foo.read();
// GET /rest/api/foo/
client.foo.read(42);
// GET /rest/api/foo/42/
client.foo.read('forty-two');
// GET /rest/api/foo/forty-two/

Retrieving Results (Uses jQuery's $.Deferred)

var client = new $.RestClient('/rest/api/');

client.add('foo');

var request = client.foo.read();
// GET /rest/api/foo/
request.done(function (data, textStatus, xhrObject){
  alert('I have data: ' + data);
});

// OR simply:
client.foo.read().done(function (data){
  alert('I have data: ' + data);
});

More Examples

Nested Resources
var client = new $.RestClient('/rest/api/');

client.add('foo');
client.foo.add('baz');

client.foo.read();
// GET /rest/api/foo/
client.foo.read(42);
// GET /rest/api/foo/42/

client.foo.baz.read();
// GET /rest/api/foo/???/baz/???/
// ERROR: jquery.rest: Invalid number of ID arguments, required 1 or 2, provided 0
client.foo.baz.read(42);
// GET /rest/api/foo/42/baz/
client.foo.baz.read('forty-two',21);
// GET /rest/api/foo/forty-two/baz/21/
Basic CRUD Verbs
var client = new $.RestClient('/rest/api/');

client.add('foo');

// C
client.foo.create({a:21,b:42});
// POST /rest/api/foo/ (with data a=21 and b=42)
// Note: data can also be stringified to: {"a":21,"b":42} in this case, see options below

// R
client.foo.read();
// GET /rest/api/foo/
client.foo.read(42);
// GET /rest/api/foo/42/

// U
client.foo.update(42, {my:"updates"});
// PUT /rest/api/42/   my=updates

// D
client.foo.destroy(42);
client.foo.del(42);
// DELETE /rest/api/foo/42/
// Note: client.foo.delete() has been disabled due to IE compatibility
Adding Custom Verbs
var client = new $.RestClient('/rest/api/');

client.add('foo');
client.foo.addVerb('bang', 'PATCH');

client.foo.bang({my:"data"});
//PATCH /foo/bang/   my=data
client.foo.bang(42,{my:"data"});
//PATCH /foo/42/bang/   my=data
Basic Authentication
var client = new $.RestClient('/rest/api/', {
  username: 'admin',
  password: 'secr3t'
});

client.add('foo');

client.foo.read();
// GET /rest/api/foo/
// With header "Authorization: Basic YWRtaW46c2VjcjN0"

Note: A window.btoa polyfill such as Base64.js will be required for this feature to work in IE6,7,8,9

Caching
var client = new $.RestClient('/rest/api/', {
  cache: 5, //This will cache requests for 5 seconds
  cachableMethods: ["GET"] //This defines what method types can be cached (this is already set by default)
});

client.add('foo');

client.foo.read().done(function(data) {
  //'client.foo.read' is now cached for 5 seconds
});

// wait 3 seconds...

client.foo.read().done(function(data) {
  //data returns instantly from cache
});

// wait another 3 seconds (total 6 seconds)...

client.foo.read().done(function(data) {
  //'client.foo.read' cached result has expired
  //data is once again retrieved from the server
});

// Note: the cache can be cleared with:
client.cache.clear();
Override Options
var client = new $.RestClient('/rest/api/');

client.add('foo', {
  stripTrailingSlash: true,
  cache: 5
});

client.foo.add('bar', {
  cache: 10,
});

client.foo.read(21);
// GET /rest/api/foo (strip trailing slash and uses a cache timeout of 5)

client.foo.bar.read(7, 42);
// GET /rest/api/foo/7/bar/42 (still strip trailing slash though now uses a cache timeout of 10)
Fancy URLs
var client = new $.RestClient('/rest/api/');

Say we want to create an endpoint /rest/api/foo-fancy-1337-url/, instead of doing:

client.add('foo-fancy-1337-url');

client['foo-fancy-1337-url'].read(42);
// GET /rest/api/foo-fancy-1337-url/42

Which is bad and ugly, we do:

client.add('foo', { url: 'foo-fancy-1337-url' });

client.foo.read(42);
// GET /rest/api/foo-fancy-1337-url/42
Query Parameters
var client = new $.RestClient('/rest/api/');

client.add('foo');

client.foo.read({bar:42});
// GET /rest/api/foo/?bar=42

client.foo.create({ data:7 }, { bar:42 });
// POST /rest/api/foo/?bar=42 with body 'data=7'

client.foo.read({ data:7 }, { bar:42 });
// GET has no body!
// GET /rest/api/foo/?bar=42&data=7
Show API Example
var client = new $.RestClient('/rest/api/');

client.add('foo');
client.add('bar');
client.foo.add('baz');

client.show();

Console should say:

ROOT: /rest/api/
  foo: /rest/api/foo/:ID_1/
    create: POST
    read: GET
    update: PUT
    delete: DELETE
    baz: /rest/api/foo/:ID_1/baz/:ID_2/
      create: POST
      read: GET
      update: PUT
      delete: DELETE
  bar: /rest/api/bar/:ID_1/
    create: POST
    read: GET
    update: PUT
    delete: DELETE
Simplify client
var client = new $.RestClient('/rest/api/');

client.add('forum');
client.forum.add('post');
client.forum.post.add('comment');

Instead of:

client.forum.post.comment.read(42,21,7);
client.forum.post.comment.update(42,21,7, {...});

You can do:

var comment = client.forum.post.comment;
comment.read(42,21,7);
comment.update(42,21,7, {...});
Global Client Example
$.client = new $.RestClient('/rest/api/');

// in another file...

$.client.add('foo');

Note: This is not best practise, use RequireJS, CommonJS or similar !

Method Override Header
var client = new $.RestClient('/rest/api/');

client.add('foo');
client.foo.update(42);
// PUT /rest/api/foo/42/

client.add('bar', { methodOverride: true });
client.bar.update(42);
// POST /rest/api/bar/42/
// with header 'X-HTTP-Method-Override: PUT'
Singleton Resource Example
var client = new $.RestClient('/rest/api/');

client.add('foo');
client.foo.add('bar', { isSingle: true });
client.foo.bar.add('bazz');

client.foo.bar.bazz.read(42, 21);
// GET /rest/api/foo/42/bar/bazz/21/
//        'bar' has no id  ^

API

new $.RestClient( [ url ], [ options ] )

Instantiates and returns the root resource. Below denoted as client.

client.add( name, [ options ] )

Instaniates a nested resource on client. Internally this does another new $.RestClient though instead of setting it as root, it will add it as a nested (or child) resource as a property on the current client.

Newly created nested resources iterate through their options.verbs and addVerb on each.

Note: The url of each of these verbs is set to "".

See default options.verbs here.

client.addVerb( name, method, [ options ] )

Instaniates a new Verb function property on the client.

Note: name is used as the url if options.url is not set.

client.verb( [id1], ..., [idN], [data], [params])

All verbs use this signature. Internally, they are all essentially calls to $.ajax with custom options depending on the parent client and options.

ids must be a string or number.

data is a jQuery Ajax Options Object's data property. If ajax.data is set on the client this data will extend it.

params query parameters to be appended to the url

Note: A helpful error will be thrown if invalid arguments are used.

Options

The options object is a plain JavaScript option that may only contain the properties listed below.

See defaults here

Important: Both resources and verbs inherit their parent's options !

cache

A number representing the number of seconds to used previously cached requests. When set to 0, no requests are stored.

cachableMethods

An array of strings representing the HTTP method types that can be cached. Is ["GET"] by default.

verbs

A plain object used as a name to method mapping.

The default verbs object is set to:

{
  'create': 'POST',
  'read'  : 'GET',
  'update': 'PUT',
  'delete': 'DELETE'
}

For example, to change the default behaviour of update from using PUT to instead use POST, set the verbs property to { update: 'POST' }

url

A string representing the URL for the given resource or verb.

Note: url is not inherited, if it is not set explicitly, the name is used as the URL.

stringifyData

When true, will pass all POST data through JSON.stringify (polyfill required for IE<=8).

stripTrailingSlash

When true, the trailing slash will be stripped off the URL.

username and password

When both username and password are set, all ajax requests will add an 'Authorization' header. Encoded using btoa (polyfill required not non-webkit).

ajax

The jQuery Ajax Options Object

methodOverride

When true, requests (excluding HEAD and GET) become POST requests and the method chosen will be set as the header: X-HTTP-Method-Override. Useful for clients and/or servers that don't support certain HTTP methods.

request

The function used to perform the request (must return a jQuery Deferred). By default, it is:

request: function(resource, options) {
  return $.ajax(options);
}

isSingle

When true, resource is perceived as singleton:

See Singleton Resource Example

autoClearCache

When false, non-cachable requests (PUT, POST or DELETE - those not in cachableMethods) won't automatically clear the request's entry in the cache.

Note: Want more options ? Open up a New Feature Issue above.


Conceptual Overview

This plugin is made up nested 'Resource' classes. Resources contain options, child Resources and child Verbs. Verbs are functions that execute various HTTP requests. Both new $.RestClient and client.add construct new instances of Resource, however the former will create a root Resource with no Verbs attached, whereas the latter will create child Resources with all of it's options.verbs attached.

Since each Resource can have it's own set of options, at instantiation time, options are inherited from parent Resources, allowing one default set of options with custom options on child Resources.

Todo

  • CSRF
  • Add Tests

Contributing

See CONTRIBUTING.md

Change Log

  • v1.0.0 - Stable v1. Added isSingle and autoClearCache by @stalniy
  • v0.0.6 - Added methodOverride option
  • v0.0.5 - Minor bug fixes
  • v0.0.4 - Simplified API
  • v0.0.3 - Added into the jQuery Plugin Repo
  • v0.0.2 - Bug fixes
  • v0.0.1 - Beta Version

githalytics.com alpha

MIT License

Copyright © 2014 Jaime Pillora [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Analytics

jquery.rest's People

Contributors

jpillora avatar manelclos avatar saturation avatar timgates42 avatar yanick 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  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

jquery.rest's Issues

Allow the data argument to be a string

Since data must be passed as an object, there is no easy way to get form data and pass it into the ajax request (say on a form submission, with data using jQuery.serialize()). The magic arguments parsing in Resource.prototype.extractUrlData seems to make this impossible to fix.

Anyway, I'm not sure how to get around this, but form submission seems like a fairly common rest api necessity.

stripTrailingSlash and query parametres

When using stripTrailingSlash = true and then calling client.create({ data }, { QUERY }) then the initial setting is ignored.

Line 354 of v1.0.2 could be refactored to something else. Useful link:
http://stackoverflow.com/questions/4740364/jquery-check-and-remove-slash-from-the-end-of-url-read

Changing that line for the following should fix the issue:

        var urlEnd = url.indexOf("?");
        if(urlEnd == -1){
            urlEnd = url.length;
        }

        // Don't bother doing anything if the URL is empty
        if (urlEnd > 0){
            if (url[urlEnd - 1] == "/"){
                url = url.substr(0, urlEnd-1) + url.substr(urlEnd);
            }    
        }   

Paginated results

Imaging this example

var client = new $.RestClient('/api/')
client.add('addresses')
client.addresses.read()

The data returned is

{
    prev: null
    next: "/api/addresses?page=2"
    results: [...]
}

Is there a way for me to use the client to fetch the next page? You probably don't want to make a specific method for detecting pagination, but is there a method for simply GETting a full URL instead of using .read()?

remove last slash on single resource

when defining a isSingle resource, i think it wold be better to remove the last slash from the url.

GET /contacts/ is not GET /contacts

i did that
this.urlNoId = this.parent.url + ("/" + (this.opts.url || this.name) + "");
instead of
this.urlNoId = this.parent.url + ("" + (this.opts.url || this.name) + "/");

PS: great plugin by the way

Handling responses

Hello there!

Im really loving this, but Im having problems handling or creating code that
handles the DELETE, UPDATE and GET request responses.
Could you provide some snippets that make this more clear for me?

Would this work? :

client.foo.update.done(function(){});
// or
client.foo.delete.done(function(){});

Cant wait for your answer. Great stuff thanks.

Custom headers

Is it possible to have a custom header? I would like to add the following custom headers:

  1. X-Requested-With: jquery
  2. Content-type: text/xml

PATCH - Custom Verbs

Hy,
Why it's not possible to make PATCH request like a POST or GET request ?
If you want make a PATCH request, you need to add custom verb (why ? It's an HTTP standard method) and problem is you can't have a correct url because custom verb is added to url :

client.add('foo');
client.foo.addVerb('bang', 'PATCH');

Result query:

PATCH /foo/bang/

Is it possible to remove this verb added or there another solution ?
Thanks for your work

stringifyData encoding GET

Howdy

The documentation states:

stringifyData

When true, will pass all POST data through JSON.stringify (polyfill required for IE<=8).

However it seems to encode all data, so a GET request has its parameters also encoded.
e.g.

 api.thing.read('id', { limit: 1 });
 http://.../thing/id?{limit:%201}

To fix this I added:

--- a/lib/jquery.rest.js
+++ b/lib/jquery.rest.js
@@ -344,7 +344,8 @@ Resource = (function() {
       encoded = encode64(this.opts.username + ":" + this.opts.password);
       headers.Authorization = "Basic " + encoded;
     }
-    if (data && this.opts.stringifyData) {
+    if (data && this.opts.stringifyData && (method !== 'GET')) {

Might not be the right fix but fixed the problem for now.

Scott

Custom Headers

Is it possible to add custom headers to POST method.

I need to Add "api_key" : apikey
and
"auth_key" : authkey in the header with my POST request. How can i do it?

Bloqueado carregamento de conteúdo ativo mesclado

Estou com um problema, quando uso a api ela funcionando perfeitamente, porem de uns dias para ca, com atualização do mozila firefox.
Esta dando erro quando acessado a api via Firefox, no console apresenta o seguinte erro: Bloqueado carregamento de conteúdo ativo mesclado

Você ja passou por isso?
Aproveitando para agradecer por essa lib, que realmente deixa muito pratico e legível as requisição ajax. Parabéns!

[enhancement] Add missing bower.json.

Hey, maintainer(s) of jpillora/jquery.rest!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library jpillora/jquery.rest is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "jpillora/jquery.rest",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

Access to HTTP return codes

One important part of working with REST services is the usage of HTTP return codes. I can't see anywhere in the documentation of jquery.rest where HTTP return code number is available. The done() handler has just one parameter - the HTTP response body. But where can I get the response code number? Please either add this important feature to the library, or document it properly if it is already present somewhere.

Delete records with parameters

Hey,

thanks for the great work!
I need to delete some specific rows in my db with other cols like ID. I use the REST API of @mevdschee and now I have to create a url like this, to delete specific rows:

api.php/categories?filter=name,sw,Inter

I tried the parameters of your REST client like this:

$.api.AromenClipboard.del({filter: 'User_ID,eq,'+getUserData().ID}).done(function (data){
                                var table = $('#aromenclipboard').DataTable();
                                table.ajax.reload( function ( json ) {

                                } );
                              });

The filter is correctly set, when I watch the network traffic:
bildschirmfoto 2016-04-17 um 01 13 12

Do you support parameters within .delete()? As now, I suppose not. Or I only don't understand how to get that working. Would be nice if you can assist me.

Greetings!

Parameter to pass on every read()

For my API on the sever I need to pass &transform=1 to get structured data to read.
Is there any convenient way to pass this on every call without changing all calls?

stringifyData doesnt change ajax.contentType

Hi,

I've encountered a minor issue: when I set stringifyData option to true, request is sent with Content-Type: application/x-www-form-urlencoded; charset=UTF-8 header.

That can be worked around by setting content-type simultaneously with stringifyData, but it would be more convenient if the library did it itself.

Convert to JavaScript for improved collabortation

Although CoffeeScript is awesome, not everyone is familiar with it. So, to improve the community's ability to collaborate, the source src/jquery.coffee.coffee should be translated to .js. Note, this repos build should still work with .js files instead of .coffee files, however, if plain Grunt is prefered over Grunt Source, the Grunt files may be copied out of Grunt Source JS Lib to this repo.

CSRF example: Django Rest Framework

Can you add following example to documentation
Sourses:
https://gist.github.com/alanhamlett/6316427
https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
I spent some time with this, may be it will be helpful for someone.

    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    var ajaxOption = {
        beforeSend: function(xhr, settings) {
            if (settings.type == 'POST' || settings.type == 'PUT' || settings.type == 'DELETE') {
                if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                    // Only send the token to relative URLs i.e. locally.
                    xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                }
            }
        }
    };

    var client = new $.RestClient('/api/rest/', {"ajax": ajaxOption});

Content-Type header

Is there a way to set the Content Type header to requests? I couldn't figure out from the examples or the documentation.

Add ability to specify transport for rest client

It's useful to have an option which is responsible for transport functionality (backend, responder) - currently there is hard-coded $.ajax. Having such option it would be easier to test functionality which depends on rest schema by substitution its responder (e.g. localStorage, or just plain js responder). Responder handles request and can respond to it like a normal backend.

Example:

require(['rest-schema', 'lib/rest_localbackend'], function (schema, LocalBackend) {
  schema.add('todos', { backend: LocalBackend.respond });
});

It gives an ability to work with todos list only on frontend (a good way to stub the server if server functionality is still not ready for integration).

using `delete` as method name might cause trouble

I remember that I run into a problem with some browser because I used delete as method name, which is a reserved word by JavaScript. That's why it's recommended to use object['delete']() instead of of object.delete(). That leads to an ugly API which is why most of the libraries and up to use an alternative, like destroy(), remove() or del(), what jquery.rest provides as well. I'd recommend to remove the .delete() method entirely.

I'm not sure what the state is with todays browsers, just wanted to make you aware that this might cause problems.

Besides that, great API to simplify a common problem, well done!

Lovely thanks!

I just wanted to tell you that I love your work. Very much apppreciated!

Licensing?

I'm sorry I know this isn't an issue with the component as such and I don't know any other way to contact you guys, but I cannot find any licensing information.

I'd really like use this object, but without any licensing information I'd be violating your copyright if I distribute it along with my application.

My own project is AGPL licensed, so almost any open license will work for me.

ajax success/error handlers

hi.
something is wrong...
(for all requests server status is 200)

var client = new $.RestClient('/rest/api/', { stringifyData: true });
restAjaxOptions = {
    success: function(data, textStatus, jqXHR) {
       console.log("success " + jqXHR);
    },
    error: function(jqXHR, textStatus, errorThrown) {
       console.log("error " + jqXHR);
    }
};
client.add('items', {ajax: restAjaxOptions});
...
$("button[data-role='save']").on("click", function(e){
  client.items.update($("#form").serializeJSON());
});

console log:

success [object]
var client = new $.RestClient('/rest/api/', { stringifyData: true });
restAjaxOptions = {
    success: function(data, textStatus, jqXHR) {
       console.log('success ' + jqXHR);
    },
    error: function(jqXHR, textStatus, errorThrown) {
       console.log('error ' + jqXHR);
    }
};
client.add('items');
...
$("button[data-role='save']").on("click", function(e){
  client.items.update($("#form").serializeJSON(), {ajax: restAjaxOptions});
});

console log:

success undefined
error undefined

how can i pass the error handlers for each resource request?
thx.

400 response crashes browser

I have a post request that looks like this:

    # Make request
    @client().v3.create(path, options).success (data) =>
      console.log("success")
    .error (errorMessage) =>
      console.log("error")

When I make a request where I know I'll get a 400 response, I get this output:

screen shot 2016-10-14 at 7 53 50 pm

Issue is that the page has basically crashes at this point. I can't press anything or reload the site. 10-20 seconds passes and then I get this screen:

screen shot 2016-10-14 at 7 54 18 pm

So what's the correct way to handle an error response with jQuery rest?

An Id shouldn't be required when calling 'create'

Currently when using the restClient to create, if an Id isn't passed as the first argument, an error is thrown stating
'Uncaught ERROR: jquery.rest: Invalid argument: object Object. Must be strings or ints (IDs) followed by one optional plain object (data). '

When creating a new instance of a resource, which I imagine should be a POST, I don't yet know what the Id of the object will be.

TypeError: $.RestClient is not a constructor

Sorry I am a beginner with this but getting the TypeError: $.RestClient is not a constructor error in the console, when I do.

//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
/static/js/jquery.rest.js"></script>

function getSQS(id, role )
{
   var client = new $.RestClient("/api/");
   client.add(role);
   client.add(id);
   var results = client.read()

   results.done(function (data){
       alert('Results: ' + data);
});

}

I would really appreciate the help.

Thank you!

Return a the HTTP Status code in the callback

Could you please return the HTTP status code in the callback? REST APIs are heavily relying on utilizing the HTTP status codes for communicating the successfulness of the operation. The jquery ajax call returns a jqXHR object, which is a superset of the browser's xhr object, which contains the http status code.

A RESTFUL API utilizes the HTTP response code to tell whether the request was successful, failed, requires authentication, etcetcetc, and this information is not available by this library, however it should be.

Thanks.

Ajax Options

I have created the Ajax option and passed to client method

var restAjaxOptions =
{
success : function(jqXHR, textStatus, errorThrown)
{
},
error : function(jqXHR, textStatus, errorThrown)
{
alert(textStatus);
}
};

client.add('postData', {
ajax : restAjaxOptions
});

but the ajax option also got updated for all other methods.

client.add('users'); // the ajax option reflected for this method also even though it is doesn't have any ajax options

Please let us know how to put the ajax option specific to one method alone

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.