Reputation: 4984
I have a email form in Wordpress and I'm using ajax to with it.
I'm creating a nonce in the form and checking it before I send the email.
The nonce fails but the output shows it is the same nonce.
Simified code:
The email form
<form class="email-form" role="form">
<div class="form-group">
<label>Full Name</label>
<input type="text" class="email-name input-lg"/>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="email-email input-lg"/>
</div>
<input type="hidden" name="ajax-nonce" id="ajax-nonce" value="' <?php echo wp_create_nonce( 'email-nonce' ); ?>'" />
<div class="form-group email-submit">
<button class="btn-green email-submit">Send</button>
</div>
</form>
The js
$('.email-submit').on('click', function(e){
e.preventDefault();
var mc_name = $('.email-name').val();
var mc_email = $('.email-email').val();
var mc_nonce = $('#ajax-nonce').val();
alert(mc_nonce);
classData = {
'type' : 'post',
'action' : 'classajax-submit',
'dataType' : 'jsonp',
'crossDomain' : true,
'nonce' : mc_nonce,
'the_name' : mc_name,
'the_email' : mc_email,
}
$.post(TheAjax.ajaxurl, classData).done(function(result){
if(result == 'success') {
//success message
}
}, 'jsonp');
})
Functions.php
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_enqueue_script('scripts',get_template_directory_uri() . '/js/compiled/main.min.js', array('jquery'));
//
wp_localize_script( 'scripts', 'TheAjax', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
}
add_action( 'wp_ajax_nopriv_classajax-submit', 'classajax_submit' );
add_action( 'wp_ajax_classajax-submit', 'classajax_submit' );
function classajax_submit() {
$nonce = stripslashes($_POST['nonce']);
echo 'nonce in php ' . $nonce;
if ( ! wp_verify_nonce( $nonce, 'email-nonce' ) ) {
die ('Email Busted!');
}else{
}
}
Upvotes: 0
Views: 2052
Reputation: 41
You just do a little wrong here. The updated nonce field is below:
<input type="hidden" name="ajax-nonce" id="ajax-nonce" value="<?php echo wp_create_nonce( 'email-nonce' ); ?>" />
Upvotes: 0
Reputation: 10802
You could use check_ajax_referrer, there's an example in the documentation: https://codex.wordpress.org/Function_Reference/check_ajax_referer
Upvotes: 1
Reputation: 11808
First of all you need not to create hidden fields use this it will create it automatically
<?php wp_nonce_field( 'your_action', 'put_name' ); ?>
while checking if(wp_verify_nonce( $_POST[ 'put_name' ], 'your_action' ))
try this
Upvotes: 3