Ajax Post Call in Admin-Ajax. Php Returns 0 with 400 Bad Request (Wordpress)
Hi as You Can See I'm Trying to Send My Data to Admin-Ajax. Php Using Ajax Post Call Kindly Check the Code Below and the Template That I Use Is Betheme. Index...
Hi as you can see I'm trying to send my data to admin-ajax.php using ajax post call kindly check the code below and the template that I use is betheme.
index.html
$('#send-form').on('submit', function () {
$.ajax({
url : '<?php echo admin_url('admin-ajax.php'); ?>',
data : {
'action' : 'test_func',
'data':'lorem ipsum'
},
type : 'POST',
contentType: "application/json; charset=utf-8",
dataType : 'json',
success : function (callback) {
console.log(callback);
}
});
return false;
});
functions.php
function test_func () {
echo json_encode(array('res'=>'return dummy text'));
}
add_action('wp_ajax_nopriv_test_func', 'test_func');
1 Answer
As per the code of ajax no need of adding contentType: "application/json; charset=utf-8 because you are passing data as string, so contentType property is not required.
To fix the issue of getting 0 every time you just have to add wp_die() at the end of test_func method.
Here you edited code
1) jQuery Ajax Code:
jQuery('#send-form').on('submit', function () {
$.ajax({
url : '<?php echo admin_url('admin-ajax.php'); ?>',
data : {
'action' : 'test_func',
'data':'lorem ipsum'
},
type : 'POST',
// contentType: "application/json; charset=utf-8",
dataType : 'json',
success : function (callback) {
console.log(callback);
}
});
return false;
});
2) Code of functions.php
function test_func () {
echo json_encode(array('res'=>'return dummy text'));
wp_die();
}
add_action('wp_ajax_nopriv_test_func', 'test_func'); // ajax call for non-login user.
add_action('wp_ajax_test_func', 'test_func'); // ajax call for login user.