npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

pajax

v5.0.3

Published

Simple AJAX library with standard ES6 promises, requests limit and XHR2. No dependencies. Forked from https://github.com/pyrsmk/qwest

Downloads

4

Readme

pajax

pajax is a simple AJAX library based on ES6 Promises. It supports XMLHttpRequest2 special data like ArrayBuffer, Blob and FormData. It was forked from qwest.

Differences to qwest

  • Removed all dependencies and pinkyswear as a Promise polyfill. Now using standard ES6 promises.
  • Removed async option. No one needs to perform synchronous requests.
  • Removed before callback, implemented a better way to access raw XHR object.
  • Removed ability to chain request calls. I suggest to use standard Promise.all function.
  • Changed a way to modify default configuration, added a few options.
  • More clean code.

Install

npm install --save pajax

I use pajax with WebPack, Babel transpiler and es6-promises polyfill. An example on how to properly setup promises polyfill with WebPack you can find here.

Basics

const ajax = require('pajax')

ajax.`method`(`url`, `data`, `options`)
.then(function(response) {
	// Run when the request is successful
})
.catch(function(e, response) {
	// Process the error
})

The method is either get, post, put or delete.

The data parameter can be a multi-dimensional array or object, a string, an ArrayBuffer, a Blob, etc... If you don't want to pass any data but specify some options, set data to null.

The available options are :

  • dataType: post (by default), json, text, arraybuffer, blob, document or formdata (you don't need to specify XHR2 types since they're automatically detected)
  • responseType: the response type; either auto (default), json, xml, text, arraybuffer, blob or document. auto mode is only supported for xml, json and text response types; for arraybuffer, blob and document you'll need to define explicitly the responseType option
  • cache: browser caching; default is false. Also see this note
  • user: the user to access to the URL, if needed
  • password: the password to access to the URL, if needed
  • headers: an object containing headers to be sent
  • withCredentials: false by default; sends credentials with your XHR2 request (more info in that post)
  • timeout: the timeout for the request in ms; 30000 by default
  • attempts: the total number of times to attempt the request through timeouts; 1 by default; if you want to remove the limit set it to null
  • send: whether to send the request immediately or not. Default is true. If you specify false, you have to manually call send() method of the returned Promise.

Returns ES6 Promise instance with abort() (see here) and send() methods and xhr (see here) property added.

The catch handler will be executed for status codes different from 2xx; if no data has been received when catch is called, response will be null.

You can also make a request with custom HTTP method using the map() function :

ajax.map('PATCH', 'example.com', ...)
.then(function() {
	// Blah blah
})

Configuration

You can control some of the library default behaviours by changing corresponding settings in ajax.config object.

The available settings are:

  • defaultDataType: dataType to be used by default if not specified in options. Default is post.
  • defaultResponseType: responseType to be used if unable to determine it by Content-Type header in auto mode. Default is text.
  • defaultXdrResponseType. The CORS object shipped with IE8 and 9 is XDomainRequest. This object does not support PUT and DELETE requests and XHR2 types. Moreover, the getResponseHeader() method is not supported too which is used in the auto mode for detecting the reponse type. Then, the response type automatically fallbacks to default when in auto mode. If you expect another response type, you have to specify it explicitly. If you want to specify another default response type to fallback in auto mode, this is the option that controls it. Default is text.
  • autoXRequestedWith: by default, the lib adds X-Requested-With: XMLHttpRequest header to the request. You can disable it by setting this option to false. Default is true.
  • limit: maximum number of parallel requests. Default is null (no limit).

Request limit

One of the greatest library functionalities is the request limit. It avoids browser freezes and server overloads by freeing bandwidth and memory resources when you have a whole bunch of requests to do at the same time. Set the request limit and when the count is reached the library will stack all further requests and start them when a slot is free.

Let's say we have a gallery with a lot of images to load. We don't want the browser to download all images at the same time to have a faster loading. Let's see how we can do that.

<div class="gallery">
	<img data-src="images/image1.jpg" alt="">
	<img data-src="images/image2.jpg" alt="">
	<img data-src="images/image3.jpg" alt="">
	<img data-src="images/image4.jpg" alt="">
	<img data-src="images/image5.jpg" alt="">
	...
</div>
// Browsers are limited in number of parallel downloads, setting it to 4 seems fair
ajax.config.limit = 4

$('.gallery').children().forEach(function() {
	var $this = $(this)
	ajax.get($this.data('src'), {responseType: 'blob'})
	.then(function(response) {
		$this.attr('src', window.URL.createObjectURL(response))
		$this.fadeIn()
	})
})

// rewrite this example

CORS and preflight requests

According to #90 and #99, a CORS request will send a preflight OPTIONS request to the server to know what is allowed and what's not. It's because we're adding a Cache-Control header to handle caching of requests. The simplest way to avoid this OPTIONS request is to set cache option to true. If you want to know more about preflight requests and how to really handle them, read this : https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Aborting a request

You can abort a request by calling abort() method of the returned Promise.

let request = ajax.get('example.com')
.then(function(response) {
	// Won't be called
})
.catch(function(response) {
	// Won't be called either
})

// Some code

request.abort()

Access the XHR object

You can access the XHR object by the xhr field of the returned Promise. If you want to get access to it before the request is sent, you have specify send: false option to the request. In this case you have to manually send the request afterwards.

let req = ajax.get('example.com', null, { send: false })
.then(function(response) {	
})

let xhr = req.xhr // Access the XHR object
// Some code

req.send() // Send the request

Handling fallbacks

XHR2 is not available on every browser, so, if needed, you can verify the XHR version with:

if (ajax.xhr2) {
	// Actions for XHR2
} else {
	// Actions for XHR1
}

Receiving binary data in older browsers

Getting binary data in legacy browsers needs a trick, as we can read it on MDN. In this library, that's how we could handle it:

let req = ajax.get('example.com/file', null, { send: false })
.then(function(response) {
	// response is now a binary string
})
req.xhr.overrideMimeType('text\/plain; charset=x-user-defined')
req.send()

Other notes

  • Blackberry 10.2.0 (and maybe others) can log an error saying json is not supported : set responseType to auto to avoid the issue
  • If you want to set or get raw data, set dataType option to text
  • As stated on StackOverflow, XDomainRequest forbid HTTPS requests from HTTP scheme and vice versa
  • IE8 only supports basic request methods

License

MIT license