Giter VIP home page Giter VIP logo

ajax's Introduction

Ajax

Ajax module in Vanilla JS

Ajax

Build Status Coveralls Coverage Status License CONTRIBUTING

You can use this module with AMD, CommonJS or just like a method of window object!

Installation

Bower

You can install via bower (but you should avoid that):

bower install ajax

Manual installation

Just download dist/ajax.min.js file, and add dist/ajax.min.js on your HTML file:

<script src="js/ajax.min.js"></script>

NPM

npm i --save @fdaciuk/ajax

CDN

You may use a CDN to get the latest version.

CDNJS:

https://cdnjs.com/libraries/fdaciuk-ajax

GitHub:

Or you may just add the following line to your HTML file:

<script src="//cdn.rawgit.com/fdaciuk/ajax/v3.0.4/dist/ajax.min.js"></script>

Usage

AMD

define(['ajax'], function (ajax) {
  ajax().get(...)
  ...
})

CommonJS

var ajax = require('@fdaciuk/ajax')
ajax().post(...)
...

ES6 / ES2015 module

import ajax from '@fdaciuk/ajax'
ajax().put(...)

Method of window object

window.ajax().get(...)

or just

ajax().get(...)

Signature

ajax([options])

Options

Optional object with request options. See all accepted options below.

HTTP Methods

You may pass any HTTP method as you want, using method property:

var request = ajax({
  method: 'options',
  url: '/api/users',
  data: {
    user: 'john'
  }
})

request.then(function (response) {...})

For using this kind of request, you must pass url property.

The property data is optional, but may used to pass any data via body on request.

headers

An object when key is a header name, and value is a header value.

ajax({
  headers: {
    'content-type': 'application/json',
    'x-access-token': '123@abc'
  }
})

If content-type is not passed, application/x-www-form-urlencoded will be used when you pass data as a query string.

Passing data as object, application/json will be automatically used (since v3.0.0).

Note about uploads:

If you need to upload some file, with FormData, use content-type: null.

baseUrl

You can pass a baseUrl param to improve calls. Example:

const request = ajax({ baseUrl: 'http://example.com/api/v2' })
request.get('/users') // get `http://example.com/api/v2/users` url

Methods

You may use any of this methods, instead the above approach:

get(url, [data])

Get data as a JSON object.

ajax().get('/api/users')

You can pass data on get method, that will be added on URL as query string:

ajax().get('/api/users', { id: 1 })

It will request on /api/users?id=1.

post(url, [data])

Save a new register or update part of this one.

// Without headers
ajax().post('/api/users', { slug: 'john' })

// With headers
var request = ajax({
  headers: {
    'x-access-token': '123@abc'
  }
})

request.post('/login', { username: 'user', password: 'b4d45$' })

data might be a complex object, like:

ajax().post('/api/new-post', {
  slug: 'my-new-post',
  meta: {
    categories: ['js', 'react'],
    tags: ['code']
  }
})

put(url, [data])

Update an entire register.

ajax().put('/api/users', { slug: 'john', age: 37 })

delete(url, [data])

Delete a register.

ajax().delete('/api/users', { id: 1 })

Return methods

Disclaimer: these return methods are not from real Promises, and they will just being called once. If you want to work with real Promises, you should make your own abstraction.

then(response, xhrObject)

Promise that returns if the request was successful.

ajax().get('/api/users').then(function (response, xhr) {
  // Do something
})

catch(responseError, xhrObject)

Promise that returns if the request has an error.

ajax().post('/api/users', { slug: 'john' }).catch(function (response, xhr) {
  // Do something
})

always(response, xhrObject)

That promise always returns, independent if the status is done or error.

ajax().post('/api/users', { slug: 'john' }).always(function (response, xhr) {
  // Do something
})

Abort request

If a request is very slow, you can abort it using abort() method:

const getLazyUser = ajax().get('/api/users/lazy')

const timer = setTimeout(function () {
  getLazyUser.abort()
}, 3000)

getLazyUser.then(function (response) {
  clearTimeout(timer)
  console.log(response)
})

In the above example, if request is slowest than 3 seconds, it will be aborted.

Deprecated methods

You may see the deprecated methods here

Contributing

Check CONTRIBUTING.md

Code coverage and Statistics

https://github.com/reportz/ajax

Browser compatibility

Chrome Firefox IE Edge Opera Safari
Latest ✔ Latest ✔ 9+ ✔ Latest ✔ Latest ✔ 3.2+ ✔

License

MIT © Fernando Daciuk

ajax's People

Contributors

andersonfelix avatar brunoventura avatar fdaciuk avatar mkxml avatar nlemoine avatar suissa 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

ajax's Issues

Browser logos are broken on README

Hey guys,

I noticed that the browser support logos are not showing properly on README.

It looks like alrra/browser-logos switched the location of the image files to another directory, they are located inside a src folder now.

Also, since the repo was using PNG logos we could take the opportunity to switch to SVG ones (they look better on HiDPI displays).

I could put up a PR for this if wanted.

Thanks!

how get the jsonp url

link this

$.ajax({
url:url,
dataType:'jsonp',
jsonp:'callback',
success:function(res) {
},
timeout:3000
});

ES6 / ES2015 module import

How can one import the ajax method, or basically anything from your ajax.min.js if the export keyword isn't used anywhere in your code? I'm confused. it that even possible?

Use fetch with XMLHttpRequest fallback?

Because I found some information about fetch and improved browser support. Should XMLHttpRequest replaced by fetch with a fallback for unsupported browsers like IE or some mobile browsers?

Error when using method options

I've tried like this

var request = ajax({
  method: 'options',
  url: '/api/users',
  data: JSON.stringify({
    user: 'john'
  })
});

request.then(function (response) {...});

but I got error request.then is not a function?
what's wrong?

Shouldn't 2.3.1 be a new minor version?

Hi There,

Nice project! Have been using it in a couple of projects, works good. The docs state the following;

Passing data as object, application/json will be automatically used (since v2.3.1).

Shouldn't that be a minor (or even major) SemVer? E.g. 2.4.0? Had my dependencies set to ^2.3.0 and after a update my whole project stopped working.

Minor issue, easy fix, but took some time to figure out what had changed (until i read your docs again).

Thanks!

Add option for base URL

First things first: BADASS plugin! Saving me big time! 😄

A common thing when consuming REST APIs via CORS is always using the same base URL for all AJAX calls. E.g.

ajax().get('https://my-url.here/service/etc')
ajax().get('https://my-url.here/service/abc')
ajax().get('https://my-url.here/service/something')
ajax().get('https://my-url.here/service/another-something')

This gets overwhelming to type for each single new AJAX call. Maybe it would be interesting to enable user to set a base URL from where requests would start from? E.g.

ajax().registerBaseUrl('https://my-url.here/service')

ajax().get('/etc')
ajax().get('/abc')
ajax().get('/something')
ajax().get('/another-something')

then if user really needs to use another URL they could just start the request with http|https (or another major protocol). E.g.

ajax().registerBaseUrl('https://my-url.here/service')

ajax().get('/etc')                                 // https://my-url.here/service/etc
ajax().get('https://another-service.here/data')    // https://another-service.here/data

Do you think its a good idea?

Help!!

How to change this code to "fdaciuk/ajax" ? Help!!
$.ajax({ url: url, contentType: false, data: FormObj, processData: false, type: 'POST', cache: false, success: function(){ .... }, error: function(){ ..... } });

Browser Compatibility

Hi fdaciuk,

Could you confirm what are the browser version that fully supports your package?

Cheers
E

about send multipart/formdata

Hi,

When we set 'content-type': 'multipart/formdata' and send formdata. The server will return error, due to no boundary in the 'content-type'.

I think we can when setting the 'content-type' to false, do not set content-type in header. like

      if ($private.hasContentType(headers) === undefined) {
        headers['Content-Type'] = 'application/x-www-form-urlencoded'
      }

what do you think?

reference: http://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax

Get HTML data

My data is in HTML format.

I tried this:

var test = ajax({
	method: 'get',
	url: '/ajax',
	baseUrl: '<?php echo u(); ?>'
});
console.log(test);

I got an object back with abort, always, catch, then. How can I get the plain html from that object?

BeforeSend

Hey Fernando,
want to add BeforeSend and Complete in lib ?
It would be nice to use loading gif ;)

Multiple .then calls will only fire the last .then callback

I have two modules that call .then on the promise returned from an ajax().post call.

// module 1
proto.method = function () {
  return ajax().post(...).then(function (response) {
    // This will not fire if there's a `then` call in module2.method
  });
};

// module 2
proto.method = function () {
  module1.method().then(function (response) {
    // This will fire because it was the last .then to be invoked
  });
};

Only the last callback "registered" with a then call will be invoked. As this is promise-based, I expect to be able to chain then/catch/always calls.

Missing character causes error

The js ends with:

 return ajax
})

That cases and error if I merge it with other javascripts.

Change it to:

 return ajax
});

Error

Hey. I caught this error
Unhandled rejection ReferenceError: XMLHttpRequest is not defined

in my controller i'm add your module like that:
ajax = require('@fdaciuk/ajax')

then
const aQuery = ajax({ baseUrl: 'https://some-site/api/'})

and then request
aQuery.post('/user/nop', { headers: { 'content-type': null }, data: { password: res.dataValues.password, username: res.dataValues.username } });

After I got the error I added:
XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest, xhr = new XMLHttpRequest()

and it did not help. Are there any ideas about this?

Call blocked: Origin 'null' is therefore not allowed access

Found #26 with the set header example

var request = ajax({
  headers: { 'content-type': null }
})

request.post(url, FormObj)
  .then(function (data) {
    // success
    console.log(data)
  })
  .catch(function (err) {
    // error
    console.log(err)
  })

Tried to add the header and send the call with one single ajax() method call.

      $.ajax({
            method: 'get',
            url: 'https://www.google.de'
        })
        $.ajax({
            method: 'get',
            headers: {
                'Access-Control-Allow-Origin': '*'
            },
            url: 'https://www.google.de'
        })

And geht errors:

without header

XMLHttpRequest cannot load https://www.google.de/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

and with header

XMLHttpRequest cannot load https://www.google.de/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.

So maybe I tried it the wrong way? Could you help me with a hint about the problem?

"Promise" api is not a proper thenable

Converting ajax "promises" into real Promises with Promise.resolve doesn't work. Successful case is fine. However, if there's an error (or abort), catch in the wrapping Promise doesn't get called.

Changing the .then(onFulfilled) method to be .then(onFulfilled, onRejected), would make this a proper thenable and allow any promise library to wrap it.

const req = ajax({/* ... */});
const realPromise = Promise.resolve(req);
realPromise
  .then(() => console.log('worked')
  .catch(() => console.log('failed'))
// 'failed' will never show if an error happens

https://jsfiddle.net/w90fk864/1/

Add non-minified source on NPM

Any chance the non-minified source could be included in the NPM distribution? I'm including ajax from NPM via webpack. The non-minified source would allow webpack to generate usable sourcemaps for ajax.

add 'get' data support

xhr.send(data) will ignore data while the method is GET,so i decide to serialize data and put it in the end of url
just like this:

//other my code
if (opt.type === 'GET' && opt.data2send !== null) {
if (url.indexOf('?') === -1) {
url += '?';
} else {
url += '&';
}
url += serilizeData(opt.data2send);
}
//other my code
function serializeData(data) {
if ('object' === typeof data) {
return _.map(data, function (key, value) {
return [key, '=', ('object' === typeof value ? JSON.stringify(value) : String(value))].join('');
}).join('&');
} else {
return String(data);
}
}
so , if you can add get 'data' support in this project?
thank you very much.

Send [object object] from method PUT

Hi @fdaciuk, i`m try to send a object to endpoint, but the network in browser show [object object].

my code:

  let url = 'http://localhost:3000/api'
  let request = (param, data) = ajax({
    method: "put",
    url: url + param,
    data: data,
  }); 

  request(`/users/1`, { driverDocument: { status: 2 } }).then()

Network

captura de tela 2018-06-19 as 09 15 46

NPM Ignoring “dist” Directory

When this is installed with NPM the dist directory seems to be ignored:

node_modules/@fdaciuk$ tree -a
.
└── ajax
    ├── .npmignore
    ├── LICENSE.md
    ├── README.md
    └── package.json

NPM seems to only have v0.0.6 registered. That might be the problem?

Posso trocar o ajaxForm() do jQuery por essa lib?

Utilizo o ajaxForm, do jQuery em alguns projetos, posso trocar por essa lib, @fdaciuk?

Um exemplo do ajaxForm em um projeto.

$('#contact').__proto__.ajaxForm({
	success: function(data) {
		location.assign(data.url);
		if (data.status) {
			$('#contact')[0].reset();
		}
	}, 
	error: function() {
		alert("Mensagem não pode ser enviada, entre em contato diretamente por e-mail");
	}
}); 

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.