Have been looked at the WP ajax documentation for hours now and still can't figure this out. I am working on a plugin and this is for updating it's options without having to refresh the page. I've managed to accomplish it through wp-load, but know thats bad practice and would like to do it correctly.
I will be moving the javascript to a separate .js file, once I have everything up and working.
All of the code is in on single page. Trying to update some options via ajax and it just is not working. The response is saying its successful, but the current_form option is not being updated. Any help would be greatly appreciated.
Code is now updated to:
wp_enqueue_script( 'AWNT_save_form_data', plugin_dir_url( __FILE__ ) . 'includes/save_form_data.js', array( 'jquery' ) );
wp_localize_script( 'AWNT_save_form_data', 'MyAjax', array(
// URL to wp-admin/admin-ajax.php to process the request
'ajaxurl' => admin_url( 'admin-ajax.php' ),
// generate a nonce with a unique ID "myajax-post-comment-nonce"
// so that you can check it later when an AJAX request is sent
'postCommentNonce' => wp_create_nonce( 'myajax-post-comment-nonce' ),
)
);
add_action('wp_ajax_AWNT_save', 'AWNT_save_callback');
function AWNT_save_callback() {
update_option('current_form', '5');
$nonce = $_POST['postCommentNonce'];
if ( ! wp_verify_nonce( $nonce, 'myajax-post-comment-nonce' ) )
die ( 'Busted!');
update_option('current_form', 'foo');
echo get_option('current_form');
die();
}
JS file (save_form_data.js) :
jQuery(document).ready(function($) {
$('#save').click(function() {
var data = {
action: 'AWNT_save',
postCommentNonce : MyAjax.postCommentNonce,
form_name : $('#form_name').val(),
customC: $('#customC').is(":checked"),
no_throttle: $('#no_throttle').is(":checked"),
form_code : $('#form_code').val()};
jQuery.post( MyAjax.ajaxurl, data, function(response) {
alert('Response: ' + response);
});
});
});
Script is being added, see an alert for the response of 0, but the update_option either isn't being called or isn't working. current_form remains the same.
I did a quick test(crude one) and this was the working code for me.
The Javascript code was:
I think the same should work for you unless you are having any other javascript conflicts.
This should be
I mean the hook name is wrong.
You should read http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/
First separate the javascript file and use wp_enqueue_script to add it. Then use wp_localize_script to pass the nonce and ajaxurl to your javascript file.
In function.php
In your javascript file