Skip to content

Instantly share code, notes, and snippets.

@uptimizt
Created October 4, 2018 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uptimizt/80874fd76be15a0881f1a234c6f9744d to your computer and use it in GitHub Desktop.
Save uptimizt/80874fd76be15a0881f1a234c6f9744d to your computer and use it in GitHub Desktop.
AJAX wrapper for native JavaScript and WordPress REST API
/**
* AJAX обертка для WordPress REST API
*/
let sb_ajax = function ( ep, success, error, type = 'GET', data = '' ) {
url = wpApiSettings.root + ep;
// Feature detection
if ( !window.XMLHttpRequest ) return;
// Create new request
var request = new XMLHttpRequest();
// Setup callbacks
request.onreadystatechange = function () {
// If the request is complete
if ( request.readyState === 4 ) {
// If the request failed
if ( request.status !== 200 ) {
if ( error && typeof error === 'function' ) {
error( request.responseText, request );
}
return;
}
// If the request succeeded
if ( success && typeof success === 'function' ) {
success( request.responseText, request );
}
}
};
// Get the HTML
request.open( type, url );
if(type != 'GET'){
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
}
request.setRequestHeader("X-WP-Nonce", wpApiSettings.nonce);
if(data){
request.send(JSON.stringify(data));
} else {
request.send();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment