Skip to content

Instantly share code, notes, and snippets.

@Kelderic
Last active January 23, 2019 16:08
Show Gist options
  • Save Kelderic/210905301cae2539b425a43292147793 to your computer and use it in GitHub Desktop.
Save Kelderic/210905301cae2539b425a43292147793 to your computer and use it in GitHub Desktop.
Ajax Without jQuery
window.ajax = function( params ) {
var method = 'method' in params ? params['method'] : 'get';
var queryURL = 'queryURL' in params ? params['queryURL'] : '';
var data = 'data' in params ? params['data'] : '';
var dataArray = [];
var dataString = '';
var successCallback = 'success' in params ? params['success'] : function(params){console.log('Successfully completed AJAX request.')};
var errorCallback = 'error' in params ? params['error'] : function(params){console.log('Error during AJAX request.');};
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function () {
if ( ajaxRequest.readyState === 4 ) {
if ( ajaxRequest.status === 200 ) {
successCallback(ajaxRequest.responseText, ajaxRequest.status);
} else {
errorCallback(ajaxRequest.responseText, ajaxRequest.status);
}
}
};
switch ( typeof data ) {
case 'string':
dataString = data;
break;
case 'object':
for ( key in data ) {
dataArray += key + '=' + data[key];
}
dataString = dataArray.join('&');
break;
}
if ( queryURL.includes('?') ) {
var tempArray = queryURL.split('?');
queryURL = tempArray[0];
dataString = ( dataString == '' ? tempArray[1] : tempArray[1] + '&' + dataString );
}
if ( method.toLowerCase() == 'post' ) {
ajaxRequest.open(method, queryURL, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send( dataString );
} else {
ajaxRequest.open(method, queryURL + ( dataString == '' ? '' : '?' + dataString ), true);
ajaxRequest.send( null );
}
};
@Kelderic
Copy link
Author

Recent update allows data to be passed as an object as well as string.

ajax({
    method: form.method,
    queryURL: form.action,
    data: {
        key1: 'value',
        key2: 'value',
    },
    success: function(data, status){
        data = JSON.parse(data);
        // Do stuff with data.
    }
    failure: function(data, status) {
        // tell user that things failed.
    }
});

@Kelderic
Copy link
Author

Latest update allows for data in the action of form element. Example, both of the below would function identically:

<form method="get" action="/rest-api/">
    <input type="hidden" name="user-action" value="update" />
    <input type="hidden" name="user" value="a.smith" />
</form>

<form method="get" action="/rest-api/?user-action=update&user=a.smith"></form>

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