Last active
January 23, 2019 16:08
-
-
Save Kelderic/210905301cae2539b425a43292147793 to your computer and use it in GitHub Desktop.
Ajax Without jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Latest update allows for data in the action of form element. Example, both of the below would function identically: