Coder Social home page Coder Social logo

ic-ajax's Introduction

ic-ajax

Build Status

Ember-friendly jQuery.ajax wrapper.

  • returns RSVP promises
  • makes apps more testable (resolves promises with Ember.run)
  • makes testing ajax simpler with fixture support

Installation

bower install ic-ajax

... or ...

npm install ic-ajax

Module Support

Note the dist directory has multiple module formats, use whatever works best for you.

  • AMD

    define(['ic-ajax'], function(ajax) {});

  • Node.JS (CJS)

    var ajax = require('ic-ajax')

  • Globals

    var ajax = ic.ajax;

    All instructure canvas stuff lives on the ic global.

API

This lib simply wraps jQuery.ajax with two exceptions:

  • success and error callbacks are not supported
  • does not resolve three arguments like $.ajax (real promises only resolve a single value). request only resolves the response data from the request, while raw resolves an object with the three "arguments" as keys if you need them.

Other than that, use request exactly like $.ajax.

var ajax = ic.ajax;

App.ApplicationRoute = Ember.Route.extend({
  model: function() {
    return ajax.request('/foo');
  }
}

// if you need access to the jqXHR or textStatus, use raw
ajax.raw('/foo').then(function(result) {
  // result.response
  // result.textStatus
  // result.jqXHR
});

Simplified Testing

In order to test newly added code you must rebuild the distribution.

broccoli build dist

Adding fixtures with defineFixture tells ic-ajax to resolve the promise with the fixture matching a url instead of making a request. This allows you to test your app without creating fake servers with sinon, etc.

Example:

ic.ajax.defineFixture('api/v1/courses', {
  response: [{name: 'basket weaving'}],
  jqXHR: {},
  textStatus: 'success'
});

ic.ajax.request('api/v1/courses').then(function(result) {
  deepEqual(result, ic.ajax.lookupFixture('api/v1/courses').response);
});

To test failure paths, set the textStatus to anything but success.

Contributing

Install dependencies and run tests with the following:

npm install
npm test

For those of you with release privileges:

npm run-script release

Special Thanks

Inspired by discourse ajax.

License and Copyright

MIT Style license

(c) 2014 Instructure, Inc.

ic-ajax's People

Contributors

aaronshaf avatar austinspomer avatar balinterdi avatar fivetanley avatar machty avatar rwjblue avatar ryanflorence 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

ic-ajax's Issues

jsonp

I'm having trouble when hitting an endpoint that uses jsonp. (tumblr, in my case).
Same Origin is telling me though shall not pass, though.

This works

  var url = api_endpoint + '&callback=?'
  return $.getJSON(url).then(function(payload){
    return payload;
  })

But this doesn't

  var url = api_endpoint + '&callback=?'
  return ic.ajax.raw(this.get('endpoint')).then(function(payload){
     return payload
   });

Problems with Ember-Data

I'm no expect in Ember or ic-ajax, but I wanted to point out something that caused me a great amount of distress.

While building an Ember app with Ember-CLI (and Ember-Data), I came across a problem with ic-ajax that I cannot fully understand. At some point ic-ajax reopens the RESTAdapter and overrides the ajax method. This monkey patch took me a really long time to track down and causes some issues with Ember-Data that I do not fully understand.

In my situation, it seemed like ic-ajax did not handle the error states in the same way the RESTAdapter is supposed to. Specifically, when my server returned a 422 with a well formed hash of errors, ic-ajax failed to trigger Ember-Data properly and the record was never put into an invalid state, nor was the DS.InvalidError object properly populated.

I fixed the problem by re-monkeypatching the RESTAdapter to it's original state, but wanted to flag this issue so that it can be properly investigated.

It's possible this problem is isolated to me but I thought I would raise this issue just in case other people were finding the same problem.

error handling in an ember-cli environment?

Hey,

Apologies if this is answered elsewhere, I haven't managed to find it.

What's the best way to me to handle errors from ic-ajax in an ember-cli environment? I'm specifically trying to log my user out of ember-simple-auth after a 401 response from the server.

I'd like to define it globally if possible.

Is there a canonical way to do this? At the moment I'm using a mixin method in the promise fail callback...

Many Thanks.

Set authorization header for all requests

I'm trying to drop ember simple auth in my app, and I have a combination of ajax requests with ic-ajax and ember data requests throughout my app. How can I set somewhere the authorization header for all ic-ajax requests so I don't have to go find them all and manually set the headers for each request.

Cant get all header from response

I try it with:

ajax.raw('/foo').then(function(result) {
  // result.response
  // result.textStatus
  console.log(result.jqXHR.getAllResponseHeaders())
});

It output only:

Content-Type: application/json
Cache-Control: no-cache

But there are many more headers that I dont get. This is the response:

Date    Sun, 12 Apr 2015 21:07:46 GMT
Cache-Control   no-cache
Access-Control-Allow-Origin http://0.0.0.0:4200
Access-Control-Allow-Credentials    true
Set-Cookie  sid=test-sid; expires=Sun, 12-Apr-2015 23:07:46 GMT; Max-Age=7200; path=/; httponly
Content-Length  139
Content-Type    application/json

And I need the Set-Cookie value.

What I am doing wrong?

Uncaught ReferenceError: ic is not defined

Hi, I can't find much documentation on how to actually implement this, but I've been following the npm page: https://www.npmjs.org/package/ic-ajax.

I don't have it doing anything yet, but putting

var ajax = ic.ajax; into app.js turns an error: ic is not defined.
(var ajax = require('ic-ajax')) creates a different error, require is not defined).

I've got ic-ajax installed (via npm), so I'm not sure what I need to do to get it to work.

defineFixture based on request type

There isn't a way to define fixtures based on request type.
Say in success handler of the POST request of a url, GET request of the same url is called, there isn't a hook to define the fixture for the GET request, and the fixture for the POST request will be returned which is not correct.

Here is a jsbin with the above said requirement.

The following is the route structure.

this.resource('posts',function(){
    this.route('new');
    this.resource('posts.list',function(){
      this.route('details',{path: '/:post_id'});
    });
  });

There will be a transition from the posts.new route, to the posts.list.details route, when the save action is called in the new route.

App.PostsNewRoute = Ember.Route.extend({
  actions: {
    save: function() {
      var self = this;
      ic.ajax.raw({url: '/posts',type: 'POST'}).then(function(response){
        self.transitionTo('posts.list.details',response.post.post_id);
      });
    }
  }
});

The fixture for the POST request can be defined before calling the save action.
But the fixture for the GET request can't be defined as calling the save action will transition to the posts.listroute, and there is no hook to define the fixture before the transition.

One possible solution will be to define fixtures in a two dimensional array, __fixtures__[url][type].

Syntax error on loading main.js

Hi
I am getting following error, when i try to use your library.
Uncaught SyntaxError: at ... ic-ajax/lib/main.js:9
Using chromer latest version.
Let me know if you need any information.

-Ashwin

offer

Hello friends of instructor, I would like to offer myself as an active maintainer of this project.

I would like to get the tests passing again, and have some ideas for a 3.x release.

let me know

Abort an ajax request

Hi

jQuery.ajax initally returns the jqXHR object, on which we can call the abort method.
Is there a way to abort an ajax request with ic-ajax?

No main file(s) specified in bower.json

Hi, some build tools that work with Bower inspect the bower.json file for main files. For example, gulp-bower-files throws the following exception if ic-ajax is a dependency listed in bower.json:

The bower package ic-ajax has no main file(s), use the overrides property in your bower.json

The Bower spec suggests adding a section to the bower.json to indicate the intended endpoints of the library.

Keep up the good work!

Add #json(url, options)

Would be nice to have this shortcut:

icAjax.json('/api/users/1', {
  type: 'put',
  data: {
   // user data
  }
})
.then(function (data) {
  //..
});

By default the following options are used:

dataType: 'json',                                                                            
contentType: 'application/json; charset=UTF-8',
type: 'get'

and JSON.stringify(..) is called on data.

ic-ajax no longer honors OVERRIDE_REST_ADAPTER

With commit be1ad8f ic-ajax does not honor the OVERRIDE_REST_ADAPTER setting. Below are some jsfiddles demonstrating the behavior.

With latest commit and OVERRIDE_REST_ADAPTER = false the response in console shows jqXHR.
http://jsfiddle.net/webguy/qD4V3/2/

With the previous commit and OVERRIDE_REST_ADAPTER = false the response in console is unaffected.
http://jsfiddle.net/webguy/qD4V3/3/

And finally a jsfiddle without ic-ajax included.
http://jsfiddle.net/webguy/qD4V3/4/

Using request blocks web font loading?

This happens on both Firefox and Chrome. Using a lot of request calls in setupController will make loading web fonts loaded in the <head> happen really late.

How do I set headers with ajax() method?

I want to attach request headers with ajax() method.
I tried with the following syntax, but its not working:

   var headers = {'Authorization': this.session.content.token}   
   return ajax({
            type: 'GET',
            url: "http://localhost:3000/places/" + location.latitude + "/" + location.longitude + "/2000.json",
            beforeSend: function (request) {
              request.setRequestHeader(headers);
            }
        });

But get the error in setRequestHeader:

 Error while processing route: index undefined is not a function TypeError: undefined is not a function
    at Object.jQuery.extend.ajax.jqXHR.setRequestHeader (http://localhost:4200/assets/vendor.js:9106:23)
    at Object.__exports__.default.Ember.Route.extend.model.get.getLocation.then.ajax.beforeSend (cabbyguide/routes/index.js:24:27)
    at Function.jQuery.extend.ajax (http://localhost:4200/assets/vendor.js:9259:39)
    at http://localhost:4200/assets/vendor.js:61982:17
    at initializePromise (http://localhost:4200/assets/vendor.js:59039:9)
    at new Promise (http://localhost:4200/assets/vendor.js:60635:9)
    at makePromise (http://localhost:4200/assets/vendor.js:61971:14)
    at raw (http://localhost:4200/assets/vendor.js:61930:14)
    at request (http://localhost:4200/assets/vendor.js:61917:18)
    at eval (cabbyguide/routes/index.js:20:18)

How do I set the headers?

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.