I have function:
function get_playlist(){
var result = jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
dataType: 'json',
data: {
action: 'getrandommp3',
nonce:'<?php echo wp_create_nonce( 'randmp3' ); ?>'
},
success: function(response) {
console.log(response); // All OK!
window.response = response;
var customvar = response;
return response;
}
});
console.log(window.response); // undefined
console.log(result.responseText); //undefined
console.log(customvar); //undefined
return window.response; // returning undefined
}
I need to return json variable from function. Inside success: function(response) { responce have needed content. But outside of Jquery.ajax i have problems…
This code needed for jquery mp3 player…
var playlist = get_playlist();
var myPlaylist = new jPlayerPlaylist(cssSelector, playlist, options);
myPlaylist.shuffle(true, true);
Thank you for help!
This is the way AJAX works (asynchronously). The
console.logstatements outside of thesuccessevent handler are executed before the response has been returned (so nothing has been assigned towindow.responseyet). Put the code that relies on the AJAX response inside thesuccessevent handler.Alternatively, you could make the request synchronous, but that’s usually not what you want as it can lock the browser until the response is returned.
Update (see comments and edit to question)
As I mentioned previously, you need to put all code that relies on the AJAX response inside the ready event handler: