Im trying to take form data and send it to wordpress with an ajax call. The call goes trough, 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();
}
The default jQuery ajax method is GET, so maybe that's your issue? Try adding method: 'POST' to your options:
$.ajax({
method: 'POST',
... etc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.