I’m trying how to figure out how to use AJAX correctly with WordPress: (I’ve used it on other sites, but not in WP)
I have this code in functions.php of a theme:
function jquery_stuff() {
wp_enqueue_script('jquery');
wp_enqueue_script('scriptname', get_bloginfo('template_url') . '/wibergsweb.js');
}
add_action( 'init', 'jquery_stuff');
//AJAX
add_action('wp_ajax_locationContent', 'locationContent');
function locationContent() {
echo 'batman returns';
die();
}
and this is what the jQuery looks like:
function loadLocationInfo(clickedOn) {
var locationId = clickedOn.next().attr('id');
var locationContent = $.ajax({
type: 'POST',
data:{
action: 'locationContent',
location_id: locationId
},
url: "/wp-admin/admin-ajax.php",
dataType: 'json'
});
locationContent.done(function(data) {
alert('DONE');
});
locationContent.fail(function(ts) {
alert('ERROR');
clickedOn.next('.location-info').html(ts.responseText);
$('body').css('cursor', 'pointer');
clickedOn.css('cursor', 'pointer');
});
}
$(document).on('click', 'h3', function(e) {
var tClicked = $(this);
loadLocationInfo(tClicked);
});
Why is the actual response returned in the fail
-function? (Yes, the data is correctly returned. That’s the weird part of it).
This is what happens:
1. ERROR is shown in alert-dialog.
2. The .location-info div is set to 'batman returns'
If I don’t have die() in the php like this:
function locationContent() {
echo 'batman returns';
}
Then a 0 is returned BUT that 0 is returned in the done()
-function (incorrect data returned at expected place)
Why is the actual response returned in the fail-function and how do I solve this issue? (I can’t figure out what’s going on here)
You are specifying the data type returned from the AJAX call to be JSON. However, the string you’re returning (“batman begins”) is not in JSON-format. Thus, the jQuery ajax-call will fail. Try passing your data as JSON using
json_encode
:This will fix your issue.
Furthermore, I can advise you to prefix your functions and adhere to the WordPress PHP Coding Standards (
myplugin_locationcontent
instead oflocationContent
, for example).