Im trying to take form data and send it to WordPress with an ajax call. The call goes through, but the variable does not reach the PHP script. Why is that?
I have checked, that formData holds a variable.
This is my js:
$( document ).ready( function() {
$( 'form' ).submit( function( event ) {
var formData = {'title': $('input[name=title]').val() };
$.ajax( {
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
data: {
action : 'my_ajax_action',
data : formData,
},
success:function( data ) {
console.log( data );
},
error: function( errorThrown ) {
console.log( errorThrown );
},
} );
event.preventDefault();
} );
});
This is my PHP:
add_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' );
function my_ajax_action_callback() {
$title =isset( $_POST['data'] ) ? $_POST['data'] : 'N/A';
echo $title;
die();
}
wp_create_nonceto get your js data back to php. When the nonce is created inside php you will have to set it inside yourdata:{}in your JS. Sorry for the short answer but I'm on the move. Anyway look upwp_create_nonceits pretty straight forward