Skip to content

Instantly share code, notes, and snippets.

@ksafranski
Last active December 14, 2015 11:50
Show Gist options
  • Select an option

  • Save ksafranski/5082377 to your computer and use it in GitHub Desktop.

Select an option

Save ksafranski/5082377 to your computer and use it in GitHub Desktop.
A simple, library-independent ajax function
/**
* Library-Independent AJAX Function
*
* Usage:
* --------------------------------
*
* ajax(url, { ...properties... });
* -or-
* ajax({ ...properties... });
*
* Example:
* --------------------------------
*
* ajax({
* url: 'path/to/resource',
* type: 'POST',
* async: true,
* cache: true,
* data: { foo: 'bar', baz: 'qux' },
* success: function(data, request){
* ...actions on success...
* },
* error: function(request){
* ...actions on error...
* }
* });
*
*/
function ajax() {
"use strict";
/**
* Parent object for all parameters
*/
var xhr = {};
/**
* Determine call structure
* ajax(url, { params }); or ajax({ params });
*/
if (arguments.length === 1) {
// All params passed as object
xhr = arguments[0];
} else {
// Populate xhr obj with second argument
xhr = arguments[1];
// Add first argument to xhr object as url
xhr.url = arguments[0];
}
/**
* Parameters & Defaults
*/
xhr.request = false;
xhr.type = xhr.type || "GET";
xhr.data = xhr.data || null;
if (xhr.cache || !xhr.hasOwnProperty("cache")) { xhr.cache = true; } else { xhr.cache = false; }
if (xhr.async || !xhr.hasOwnProperty("async")) { xhr.async = true; } else { xhr.async = false; }
if (xhr.success && typeof xhr.success === "function") { xhr.success = xhr.success; } else { xhr.success = false; }
if (xhr.error && typeof xhr.error === "function") { xhr.error = xhr.error; } else { xhr.error = false; }
/**
* Format xhr.data & encode values
*/
if (xhr.data) {
var param_count = 0,
name,
value,
tmp_data = xhr.data;
for (var param in tmp_data) {
if(tmp_data.hasOwnProperty(param)){
name = encodeURIComponent(param);
value = encodeURIComponent(tmp_data[param]);
if (param_count === 0) {
xhr.data = name + "=" + value;
} else {
xhr.data += "&" + name + "=" + value;
}
param_count++;
}
}
xhr.data = xhr.data;
}
/**
* Appends data to URL
* @string data The data to append
*/
function formatURL(data) {
var url_split = xhr.url.split("?");
if (url_split.length !== 1) {
xhr.url += "&" + data;
} else {
xhr.url += "?" + data;
}
}
/**
* Handle xhr.data on GET request type
*/
if (xhr.data && xhr.type.toUpperCase() === "GET") {
formatURL(xhr.data);
}
/**
* Check cache parameter, set URL param
*/
if (!xhr.cache) {
formatURL(new Date().getTime());
}
/**
* Establish request
*/
if (window.XMLHttpRequest) {
// Modern non-IE
xhr.request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// Internet Explorer
xhr.request = new ActiveXObject("Microsoft.XMLHTTP");
} else {
// No request object, break
return false;
}
/**
* Monitor ReadyState
*/
xhr.request.onreadystatechange = function () {
if (xhr.request.readyState === 4) {
if (xhr.request.status === 200) {
if (xhr.success) {
// Returns responseText and request object
xhr.success(xhr.request.responseText, xhr.request);
}
} else {
if (xhr.error) {
// Returns request object
xhr.error(xhr.request);
}
}
}
};
/**
* Open Http Request connection
*/
xhr.request.open(xhr.type, xhr.url, xhr.async);
/**
* Set request header for POST
*/
if (xhr.type.toUpperCase() === "POST") {
xhr.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
/**
* Send data
*/
xhr.request.send(xhr.data);
}
@somecallmemike
Copy link
Copy Markdown

Can this be used with the jsonp datatype?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment