3

I'm trying to add a nonce to my plugin's Ajax. I'm not sure why I'm getting this error:

Fatal error: Call to undefined function wp_create_nonce()

In my php file :

wp_localize_script('my-ajax-handle', 'the_ajax_script', array('ajaxurl'=> admin_url('admin-ajax.php'), 'my_nonce' => wp_create_nonce('myajax-nonce')));

In js file:

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

Any suggestions on how to solve this?

Thank you.

6

More context would be helpful. Is that all the code found in your plugin or functions file directly? Or are you hooking in to something via add_action.

Anyway, what's probably wrong is that you're calling wp_localize_script and wp_enqueue_script outside of an action. wp_create_nonce, or, rather, the file in which it resides, has yet to be loaded.

The solution is to call wp_localize_script from inside a function hooked into wp_enqueue_scripts

<?php
add_action( 'wp_enqueue_scripts', 'wpse30583_enqueue' );
function wpse30583_enqueue()
{
    // your enqueue will probably look different.
    wp_enqueue_script( 'wpse30583_script' );

    // Localize the script
    $data = array( 
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'nonce'    => wp_create_nonce( 'wpse30583_nonce' )
    );
    wp_localize_script( 'wpse30583_script', 'wpse3058_object', $data );
}
  • Hi, @Christopher Davis, Thank you very much for your message. You're right, I didn't have wp_localize_script inside a function. I never would have thought of your solution. I plopped it in a function and now I don't get the fatal error anymore. Unfortunately, I must have a second bug. I don't think that the nonce is being posted. Does this bit look correct: jQuery.post(the_ajax_script.ajaxurl, {my_nonce : the_ajax_script.my_nonce}, jQuery("#theForm").serialize()... Also, I tried putting an echo in php and alert on the js. It looks like the 2 numbers are different. Is this normal? Thank you. – Laxmidi Oct 10 '11 at 20:20
  • Better ask that in a separate question. Maybe someone else has had a similar issue. – chrisguitarguy Oct 10 '11 at 20:38
  • I was thinking about doing that. I'll go ahead and post a new one. Thank you very much for the help! – Laxmidi Oct 10 '11 at 20:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.