In spite of many similar posts, all the proposed solutions didn't work for me, so here we are.
I have the following script :
jQuery('#term').keyup(ajaxChange);
function ajaxChange(){
var newFormChange = jQuery("#term").val();
alert (newFormChange);
jQuery.ajax({
type:"POST",
action: "my_test_action",
url: "/wp-admin/admin-ajax.php",
data: newFormChange,
success:function(data){
console.log(data);
}
});
return false;
}
And the PHP looks like this :
function my_test_action() {
$var = "this is a test";
wp_send_json($var);
die();
}
add_action( 'wp_ajax_my_test_action', 'my_test_action' );
add_action( 'wp_ajax_nopriv_my_test_action', 'my_test_action' );
I've also tried : echo json_encode($var)
or echo $var
, instead of wp_send_json()
but the function always returns 0 in the browser console !
My other AJAX calls work, for instance I have another one that calls a PHP script which calls a WP Query and displays some posts, it works fine.
EDIT : Here is how my script is included :
function add_js() {
if (is_page_template()) {
wp_enqueue_script( 'mycustomscript', get_stylesheet_directory_uri().'/js/mycustomscript.js', array('jquery'), '1.0', true );
wp_localize_script('mycustomscript', 'ajaxurl', admin_url( 'admin-ajax.php' ) );
}
}
add_action('wp_enqueue_scripts', 'add_js');
I think the problem comes from the newFormChange
variable, because jQuery(this).serialize();
didn't work in the first place, because the form is not submitted but only one of its fields changes. So I replaced it by var newFormChange = jQuery("#term").val();
but then maybe there is a problem with url: "/wp-admin/admin-ajax.php"
Where am I mistaken ? Thanks