I’m trying a simple ajax test in WordPress / Buddypress.
The code below works fine in IE and Chrome.
But in Firefox, the javascript is called, but then it just refreshs the current page.
The are no errors in the firebug console, but the response is empty.
I don’t think the php is being called.
What do I need to change to get this working in Firefox ?
the javascript:
jQuery(document).ready(function(){
jQuery('#test-form input#save').click(function(){
jQuery('.ajax-loader').toggle();
jQuery('#save').attr({'disabled': true});
jQuery.post( ajaxurl, {
action: 'test_save',
'cookie': encodeURIComponent(document.cookie),
'_wpnonce': jQuery("input#_wpnonce-save").val(),
},
function(response) {
jQuery('.ajax-loader').toggle();
// alerts work up to here in all browsers
jQuery('#test-form').append(response);
});
});
});
the php:
add_action( 'bp_after_profile_loop_content', 'show_test', 100 );
add_action('wp_ajax_test_save', 'test_save_function');
function show_test() {
?>
<form action="#" id="test-form">
<?php wp_nonce_field( 'save', '_wpnonce-save' ); ?>
<input type="submit" name="save" id="save" value = "test ajax"/>
<span class="ajax-loader"></span>
</form>
<?php
}
function test_save_function() {
check_ajax_referer('save');
echo "php -button was clicked";
}
Note that it will work only if you are logged on to WordPress at the time! If you arenât logged in, wp_ajax calls the hook wp_ajax_nopriv_myfunction.
Links:
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)
http://www.simonbattersby.com/blog/2012/06/wordpress-wp_ajax-returning-0-error/
Hope this saves someone an hour or so…
This works in FF, Chrome and IE. Also – add die(); at end of php function