Created
January 16, 2015 00:18
-
-
Save bruno-barros/98db76c8d777caa3c414 to your computer and use it in GitHub Desktop.
WordPress AJAX object
This file contains hidden or 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
/** | |
* Ajax.send(); | |
* | |
* Usage: Ajax.send('my-handler', {"data": "value"}, ajaxurl).then(function(response){ //... }); | |
* | |
* Ajax handler to send messages to WordPress AJAX API | |
*/ | |
(function ($, window, document, undefined) { | |
window.Ajax = (function () { | |
var handler, data, ajaxUrl; | |
function send(_handler, _data, _ajaxUrl) { | |
handler = _handler; | |
data = _data; | |
return $.ajax({ | |
type: "post", | |
dataType: "json", | |
url: guessAjaxEndpoint(_ajaxUrl), | |
data: getData() | |
}); | |
} | |
function getData() { | |
var rawData = { | |
action: handler, | |
nonce: getNonce() | |
}; | |
// do not permit to overwrite the action handler | |
if (data.action !== undefined) { | |
delete data.action; | |
} | |
return $.extend(rawData, data); | |
} | |
function getNonce(){ | |
if(window.GJS.nonce !== undefined){ | |
return window.GJS.nonce; | |
} | |
return ''; | |
} | |
function guessAjaxEndpoint(url) { | |
if (url !== undefined) { | |
return url; | |
} | |
// WP admin | |
if (window.ajaxurl !== undefined) { | |
return window.ajaxurl; | |
} | |
// weloquent example | |
if (window.GJS.ajaxurl !== undefined) { | |
return window.GJS.ajaxurl; | |
} | |
if (window.GJS.ajaxUrl !== undefined) { | |
return window.GJS.ajaxUrl; | |
} | |
// something were wrong | |
return false; | |
} | |
/** | |
* Public API | |
*/ | |
return { | |
send: send | |
}; | |
})(); | |
// | |
})(jQuery, window, document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment