Using Nonce with Ajax in WordPress Plugin

I’m trying to use a nonce in a WordPress plugin. I’ve got a form that I want use the nonce on.

In php:

Read More
function csf_enqueue() {

//I have other scripts enqueued in htis function 
wp_enqueue_script('my-ajax-handle', plugin_dir_url(__FILE__).'file-path', array('jquery', 'jquery-ui-core', 'jquery-ui-datepicker', 'google-maps'));

$data = array(
    'ajax_url' => admin_url( 'admin-ajax.php' ),
    'my_nonce' => wp_create_nonce('myajax-nonce')
);

wp_localize_script('my-ajax-handle', 'the_ajax_script', $data );

}

add_action('wp_enqueue_scripts', 'csf_enqueue');
add_action('wp_ajax_the_ajax_hook', 'the_action_function');
add_action('wp_ajax_nopriv_the_ajax_hook', 'the_action_function');

In the jQuery file:

jQuery.post(the_ajax_script.ajaxurl, {my_nonce : the_ajax_script.my_nonce}, jQuery("#theForm").serialize() + "&maxLat="+ csf_dcscore_crime_map_bounds[0] + "&maxLong="+ csf_dcscore_crime_map_bounds[1] + "&minLat="+ csf_dcscore_crime_map_bounds[2] + "&minLong="+ csf_dcscore_crime_map_bounds[3],
                    function(response_from_the_action_function){
                        jQuery("#response_area").html(response_from_the_action_function);
                    });

Am I posting the nonce correctly in the jQuery?

In php:

function the_action_function() {
   if( ! wp_verfiy_nonce( $nonce, 'myajax-nonce')) die ('Busted!');
//function continues

Any suggestions? If I strip out all the code regarding the nonce, everything works fine. Any ideas as to why it’s not working? Or how can I debug it? Thank you!

Thank you.

Related posts

Leave a Reply

1 comment

  1. There are two things wrong.

    Sending data via jQuery post method, you can not send one object+one query string as you have done. Instead you will need to either send the query string format or the object format data. For ease in your case, I will go with the query string format. so the post code should look like this

    jQuery.post( the_ajax_script.ajaxurl, 
                 jQuery("#theForm").serialize() + 
                        "&maxLat="+ csf_dcscore_crime_map_bounds[0] + 
                        "&maxLong="+ csf_dcscore_crime_map_bounds[1] + 
                        "&minLat="+ csf_dcscore_crime_map_bounds[2] + 
                        "&minLong="+ csf_dcscore_crime_map_bounds[3] +
                        "&my_nonce="+ the_ajax_script.my_nonce,
                 function(response_from_the_action_function) {
                     jQuery("#response_area")
                         .html(response_from_the_action_function);
                 });
    

    That will send the nonce in the parameter my_nonce. Now server side you can replace

    if( ! wp_verify_nonce( $nonce, 'myajax-nonce')) die ('Busted!');
    

    with

    if( ! wp_verify_nonce( $_POST['my_nonce'],'myajax-nonce')) die ('Busted!');
    

    A look at the documentation of jQuery.post and wp_verfiy_nonce will help you better 🙂