Javascript AJAX (ajax.js)
INSTALATION
npm install ajax-min
DOWNLOAD
<script type="text/javascript" src="https://tomflidr.github.io/ajax.js/builds/1.0.14/ajax.min.js"></script>
<script type="text/javascript" src="https://tomflidr.github.io/ajax.js/builds/1.0.14/ajax.dev.js"></script>
DEMOS
Very effective, supersmall, cross browser AJAX library, supporting JSON, JSONP, XML, HTML or TEXT requesting or returning result type by HTTP header Content-Type, automatic data serialization, automatic evaluation by recognized type, global handlers and syntax based on jQuery.ajax();.
FEATURES
- very effective, super small javascript AJAX library - all in 460 lines, minimized: 8.3 KB, gzipped: 3.3 KB
- syntax based on jQuery.ajax();,
Ajax.load();
, Ajax.get();
, Ajax.post();
, no promisses, returning XmlHttpRequest
- supported browsers: MSIE6+, Firefox, Chrome, Safari, Opera and mobile browsers
- highly optimized
- all request methods supported -
GET
, POST
, HEAD
, OPTION
, ...
- but only
GET
in JSONP
request type (by <stript> tag, to request foreing domains without any other settings)
- still possible to request diferent domains with http header:
"Access-Control-Allow-Origin"
- automatic
JSON
serialization into format: key1=value1&key2=["anything",{"with":["JSON","structure"]}]
- data always sended with HTTP headers:
X-Requested-With: XmlHttpRequest
(posibile to change)Content-Type: application/x-www-form-urlencoded
(posibile to change)
JSON
evaluation and XML
/HTML
parsing into environment types by type param- automatic result conversion by response HTTP header
"Content-Type"
into JSON
/XML
/HTML
/TEXT
if no type
option defined - posibility to change any http header before send and read any header after data are loaded or error handled (except cookies header:-)
- posibility to change async requesting to sync (but it is not recomanded, by default is async)
- global handlers for each request to set up error loging or loading animations:
Ajax.beforeLoad(function(xhr, requestId, url, typ){});
Ajax.onSuccess(function(xhr, requestId, url, type){});
Ajax.onAbort(function(data, statusCode, xhr, requestId, url, type){});
Ajax.onError(function(responseText, statusCode, xhr, errorObject, errorEvent, requestId, url, type){});
USAGE
Include JAVASCRIPT file ajax.min.js
into your HTML page in \<head\>
section, no other library is necessary:
<script type="text/javascript" src="https://tomflidr.github.io/ajax.js/builds/1.0.9/ajax.min.js"></script>
Or include JAVASCRIPT file ajax.min.js
into your project by require()
function implemented by your own:
var Ajax = require('./node_modules/ajax-min/builds/latest/ajax.min.js').Ajax;
If you are using TypeScript, add to your tsconfig.json
file:
{
"compilerOptions": {
"typeRoots": [
"./node_modules/",
],
"types": [
"ajax-min"
],
},
}
Universal Syntax
Basic Syntax
Standard browser window.XMLHttpRequest object is returned, for JSONP
requests is returned object described later.
var xhr = Ajax.load({
url: '',
method: '',
data: {},
success: function(){},
type: '',
error: function(){},
headers: {},
async: true
});
Full Example
VIEW DEMO
Create any *.html file in base project directory and paste this code into <script> tag:
<div id="result"></div>
<script type="text/javascript">
var xhr = Ajax.load({
url: 'demos/data/json.php',
method: 'post',
data: {
key1: "value1",
key2: [
"anything",
{"with": ["JSON", "structure"]}
]
},
success: function (data, statusCode, xhr, requestId, url, type) {
result.innerHTML = "<pre><code>Result data:\n" + JSON.stringify(data, null, 4) + "</code></pre>";
},
type: 'json',
error: function (responseText, statusCode, xhr, requestId, url, type) {
console.log(arguments);
},
async: true,
headers: {
}
});
</script>
GET Request
Basic Syntax
Standard browser window.XMLHttpRequest object is returned, for JSONP requests is returned object described later.
var xhr = Ajax.get(
url,
data,
success,
type,
error,
headers,
async
);
Full Example
VIEW DEMO
Create any *.html file in base project directory and paste this code into <script> tag:
<div id="result"></div>
<script type="text/javascript">
var xhr = Ajax.get(
'demos/data/json.php',
{
key1: "value1",
key2: [
"anything",
{"with": ["JSON", "structure"]}
]
},
function (data, statusCode, xhr, requestId, url, type) {
result.innerHTML = "<pre><code>Result data:\n" + JSON.stringify(data, null, 4) + "</code></pre>";
},
'json',
function (responseText, statusCode, xhr, requestId, url, type) {
console.log(arguments);
}
);
</script>
POST Request
Basic Syntax
Standard browser window.XMLHttpRequest object is returned, for JSONP requests is returned object described later.
var xhr = Ajax.post(
url,
data,
success,
type,
error,
headers,
async
);
Full Example
VIEW DEMO
Create any *.html file in base project directory and paste this code into <script> tag:
<div id="result"></div>
<script type="text/javascript">
var xhr = Ajax.post(
'demos/data/xml.php',
{
key1: "value1",
key2: [
"anything",
{"with": ["JSON", "structure"]}
]
},
function (data, statusCode, xhr, requestId, url, type) {
result.innerHTML = "<pre><code>Result data:\n"
+ data.documentElement.outerHTML.replace(/\</g, '<').replace(/\>/g, '>')
+ "</code></pre>";
},
'xml',
function (responseText, statusCode, xhr, requestId, url, type) {
console.log(arguments);
}
);
</script>
GET JSONP Request
Description
For all requests with return type initialized with JSONP value is not created standard instance from browser's window.XMLHttpRequest, but there is created temporary <script> tag in <head> section of your HTML file to safely include script resource from foreing domain without any broser security Error thrown. You can load data from foreing domains also by using HTTP header "Access-Control-Allow-Origin", but it's not what is necessary to describe here.
To be clear - there is possible with JSONP to use only GET method - to send and load data from foreing domain. So be careful, there are some limitations for url length, because all params are contained in url.
Before <script> tag is appended into <head> section, there is initialized temporary public function in window.Ajax.JsonpCallback[X] to handle incoming script content. Name of this public function is sended to foreing server in GET param named as "&callback=Ajax.JsonpCallback[X]". Ajax library presume, that server always return only content with only this public function call with first argument containing result data. Be careful for server trust, there should be anything else, but it doesn't happend (but it's only a different way how to say - it happends:-). After script is loaded by browser, initialized in <head> section, then prepared public function is called. Temporary <script> tag is removed, public function is also deleted and your custom callback is called.
Return Type
Ajax.load() and Ajax.get() will not return any xhr object if you use JSONP data type to return. There is returned javascript object with three properties:
var jsonpReq = {
url
id
abort
};
If you want to manipulate with this kind of request resources, be free to do anything. Read more in source lines in function "_processScriptRequest". But to abort JSONP request - it's just only necessrry to:
var jsonpReq.abort();
Full Example
VIEW DEMO
var jsonpReq = Ajax.get(
'https://tomflidr.github.io/ajax.js/demos/data/books.json',
{
key1: "value1",
key2: [
"anything",
{"with": ["JSON", "structure"]}
]
},
function (data, statusCode, xhr, requestId, url, type) {
console.log(arguments);
},
'jsonp'
);
jsonpReq.abort();
Global Handlers
Add Global Handler
There is called queue of handlers before each request by window.XMLHttpHeader object and also before each request by JSONP requesting throught <script> tags. Also there is called a queue of handlers after each success response for these request types. To add any handler function, see full example bellow.
Full Example
VIEW DEMO
Ajax.beforeLoad(function (xhr, requestId, url, type) {
document.body.style.cursor = 'wait !important';
});
Ajax.onAbort(function (xhr, requestId, url, type) {
document.body.style.cursor = 'default';
});
Ajax.onSuccess(function (data, statusCode, xhr, requestId, url, type) {
document.body.style.cursor = 'default';
});
Ajax.onError(function (responseText, statusCode, xhr, errorObject, errorEvent, requestId, url, type) {
console.log(arguments);
});
All global handlers return Ajax library declaration function, so it's possible to init global handlers like:
Ajax.beforeLoad(function (xhr, requestId, url, type) {
document.body.style.cursor = 'wait !important';
}).onAbort(function (xhr, requestId, url, type) {
document.body.style.cursor = 'wait !important';
}).onSuccess(function (data, statusCode, xhr, requestId, url, type) {
document.body.style.cursor = 'default';
}).onError(function (responseText, statusCode, xhr, errorObject, errorEvent, requestId, url, type) {
console.log(arguments);
});
Remove Global Handler
Handlers are stored in arrays placed in:
Ajax.handlers.before = [];
Ajax.handlers.abort = [];
Ajax.handlers.success = [];
Ajax.handlers.error = [];
Feel free to use them as standard plain JS arrays to add or remove any handler anytime. There are no any static functions on Ajax object to remove handlers, so it's necessary to do it (if you want) by:
delete Ajax.handlers.before[yourDesireIndex];
Public Static Properties
HTTP default headers sended in each request by XMLHttpRequest, not in JSONP requesting.
Feel free to change it.
Ajax.defaultHeaders = {
'X-Requested-With': 'XmlHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded'
};
Ajax.jsonpCallbackParam
JSONP requesting GET param name how to say name of public callback function to server.
Specific name of the function is generated by library. As default library uses name 'callback'.
Most of JSON APIs uses standard naming convention - 'callback' value, but sometimes should be handy to change it.
Ajax.jsonpCallbackParam = 'callback';
DEV OPS
- This library doesn't need any dependency.
- To build development or minimalized version, you need to run:
- Windows:
call devel-tools/make-dev-version-from-src.cmd
call devel-tools/make-min-version-from-src.cmd
- Linux:
sh devel-tools/make-dev-version-from-src.sh
sh devel-tools/make-min-version-from-src.sh