• Stars
    star
    748
  • Rank 60,661 (Top 2 %)
  • Language
    JavaScript
  • License
    Other
  • Created over 9 years ago
  • Updated about 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Ajax module in Vanilla JS

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

More Repositories

1

conduit-api

API for Real World App project (Conduit) using Node.js + TS with Functional Programming
TypeScript
178
star
2

workflow-reactjs

My workflow with ReactJS + Webpack 3+
JavaScript
146
star
3

boilerplate-vite-react

Create a new project with React.js, TypeScript and jest with Vite
TypeScript
97
star
4

hmh

🕙 How many hours?
JavaScript
90
star
5

strclass

A ~200b library to apply CSS classes as strings from objects
JavaScript
84
star
6

dotfiles

My configuration files for zsh, neovim and tmux.
Vim Script
63
star
7

hoost

Easily manage your virtual hosts
JavaScript
62
star
8

talks

Palestras.
JavaScript
57
star
9

nodejs-ports-adapters-fp

Node.js Ports & Adapters Architecture for Functional Programming with TypeScript and fp-ts
JavaScript
50
star
10

install-linux

Softwares to install on Linux
Shell
48
star
11

react-ff

Feature Flag component for React
TypeScript
46
star
12

react-trianglify

React Wrapper Component for trianglify
CSS
38
star
13

iscpf

Validate CPF numbers (for NodeJS and browsers)
TypeScript
37
star
14

most-voted

See the most voted subjects in an event
JavaScript
33
star
15

use-timer

React Hook to easily create decremental timers.
JavaScript
28
star
16

is

Typechecker in Vanilla JS
JavaScript
26
star
17

clima

☀️ Get city weather from wttr.in
Shell
24
star
18

boilerplate-nodejs-typescript-serverless

WIP - Boilerplate for Node.js + TypeScript + Prisma + Serverless
TypeScript
18
star
19

fdaciuk

Fernando Daciuk, the person.
JavaScript
18
star
20

jaiminho

Rest application for zip codes from Brazil.
JavaScript
16
star
21

sls-rust

A Serverless framework plugin for Rust applications
JavaScript
16
star
22

hmh-cli

🕙 How many hours?
JavaScript
16
star
23

load-async

Load React components asynchronously
JavaScript
16
star
24

getmodule

Include local NodeJS modules relative to your root path
JavaScript
15
star
25

workflow-reactjs-parcel

My workflow with ReactJS + Parcel
JavaScript
15
star
26

avit-da2k

💲 oh-my-zsh theme based on avit theme
14
star
27

cargo-v

Update the version of your package easily
Rust
13
star
28

workflow-requirejs

Workflow with RequireJS
JavaScript
13
star
29

dont-stop-grooveshark

Google Chrome Extension that doesn't leave Grooveshark stop playing.
JavaScript
13
star
30

rust-serverless-examples

Examples of how to use Rust with Serverless Framework, Lambda, API Gateway v1 and v2, SQS, GraphQL, etc
Rust
13
star
31

fdaciuk.github.io

11
star
32

severino

ReScript
11
star
33

github2twitter

JavaScript
10
star
34

spawn-webpack-plugin

Run terminal commands with webpack
JavaScript
10
star
35

nostalgia

10
star
36

boleto

Generates new bar code, adding due date and value.
JavaScript
9
star
37

react-lazy-img

JavaScript
8
star
38

crypto-zombies-frontend

TypeScript
8
star
39

js-components

Javascript components to use on your web project
JavaScript
8
star
40

sorteio

Script bestinha de sorteio
JavaScript
8
star
41

workflow-nextjs

My workflow to create apps with Next.js
JavaScript
7
star
42

Passport-Facebook-Express-4

Boilerplate to authenticate with Passport Facebook + Express 4
JavaScript
7
star
43

mg-ui

React Components with Milligram
JavaScript
6
star
44

wordpress-base-theme-da2k.com.br

Este tema está sendo desenvolvido a partir da série "Como criar temas para WordPress", no link:
PHP
6
star
45

sexyforms

jQuery plugin to style form fields: select, radio, checkbox and file.
JavaScript
6
star
46

docker-stream

Live stream in more than one source at a time
5
star
47

Exemplos-Guia-essencial-do-HTML5

Exemplos do livro "O Guia essencial do HTML5 - Usando jogos para aprender HTML5 e Javascript".
JavaScript
5
star
48

freeproxies-crawler

Get proxies addresses from http://www.freeproxylists.net/
JavaScript
4
star
49

rick-and-morty-faker

Elixir
4
star
50

gatsby-starter-netlify-cms

JavaScript
3
star
51

gifs-wall-backend

JavaScript
3
star
52

reactjs-workflow

DEPRECATED - Use this instead: https://github.com/fdaciuk/workflow-reactjs
JavaScript
3
star
53

stream-adventure

Playing with streams in NodeJS
JavaScript
3
star
54

workflow-javascript

My Workflow Javascript with Module Pattern
JavaScript
3
star
55

obs-overlay

Twitch Overlay para minhas lives.
TypeScript
3
star
56

workout-webapp

https://treino.netlify.app
JavaScript
2
star
57

gifs-wall-frontend

TypeScript
2
star
58

css2json-cli

Convert CSS string to JSON
JavaScript
2
star
59

Desafios-CSS

Desafios CSS que participei
2
star
60

Google-Adwords-Broad-Matching

Add a "+" before each word.
JavaScript
2
star
61

api-loterias

TypeScript
2
star
62

node-rest

Simple Rest with Node + Express 4
JavaScript
1
star
63

i18n-example

Example of i18n on frontend
HTML
1
star
64

fillca

JavaScript
1
star
65

crypto-zombies-backend

Smart Contracts for Crypto Zombies game
Solidity
1
star
66

workout-webapp-rescript

ReScript version of Workout App
JavaScript
1
star
67

snake-game

It's an universal implementation of snake game.
1
star
68

Github-Webapp-with-ReactJS

Exemplo Github API com ReactJS
JavaScript
1
star
69

da2k-grid

Grid dinâmico com SASS para deixar seu HTML limpo :)
1
star
70

doty

My dotfiles. Made in NodeJS.
1
star
71

vagrant-php-nodejs

My Vagrant Environment with PuPHPet
Puppet
1
star
72

vow

1
star
73

send-mail-post-pending

Plugin para WordPress que envia um e-mail ao administrador do site/blog para avisar quando há novos posts para revisão.
PHP
1
star