Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm trying to securely save custom data to database from plugin backend via ajax.

JavaScript code that runs after clicking save button:

$.ajax({
    url: ajaxVars.ajaxurl,
    type: 'post',
    data: {
        action : 'myPluginDataSave',
        someData: 'blabla',
        myPluginNonce : ajaxVars.nonce
    },
    complete: function(data) {          
        console.log('finish',data.responseText);
    }
});

PHP code (some parts are missing), ajax_save_data function receives data from JS code:

add_action( 'wp_ajax_myPluginDataSave', array(&$this, 'ajax_save_data') );
wp_enqueue_script( 'my-plugn-js' );
wp_localize_script( 'my-plugn-js', 'ajaxVars', array(
                    'ajaxurl' => admin_url( 'admin-ajax.php' ),
                    'nonce' => wp_create_nonce( 'myPluginNonce' ),                          
)); 

function ajax_save_data() {
    if ( !isset($_POST['myPluginNonce']) || !wp_verify_nonce( $_POST['myPluginNonce'], 'myPluginNonce' ) ) 
        die ( 'you cant do this' ); 

    echo 'here data gets saved to DB' . $_POST['someData'];

    die();
}

Hooks are added only in admin (inside is_admin() if statement). Save button can be clicked multiple times (without page refresh).

Code works. But, my question: is this correct way to do this? Do I need nonce there?

Thank you for advice.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

I don't see any is_admin conditional statement which is why you should include it in your snippet so we can properly assess what you are attempting to do outside of the obvious question.

Either way a nonce should be mandatory. That function that receives and processes your AJAX request/response should also verify your nonce to ensure the request is a valid and secure request - even IF the request is originating from the back-end, it still could be insecure or an attempt to exploit the system.

Also look at:

share|improve this answer
    
Thank you for answer, but my question is more about multiple ajax request per one page. For example I have two buttons that send ajax request to admin - "update_calendar" and "get_date". Should I have separate nonce for every single request? Or for each button? –  Marvin3 Nov 13 '12 at 11:53
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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