I've never used ajax in wordpress before and I'm trying to make a simple ajax request by following some video tutorials on youtube but it always return this error message: Failed to load resource: the server responded with a status of 400 (Bad Request)
My javascript (inside my own template file):
jQuery.ajax({
url: ajaxurl,
type: "POST",
dataType: 'json',
data: {
action: 'my_action'
},
success: function ( response ) {
console.log("success");
alert("success");
},
error: function( error ){
console.log("error");
alert("error");
}
});
my functions.php file:
<?php
add_action('wp_ajax_my_action', 'insertEmail');
add_action('wp_ajax_nopriv_my_action', 'insertEmail');
function insertEmail(){
echo "<script> alert('functions fil'); </script>"
die();
}
?>
<script>
tags don't belong in the output, it expects pure JavaScriptajaxurl
? It is only set by default on admin screens, not the front end.add_action('wp_ajax_my_action', 'insertEmail');
toadd_action('wp_ajax_my_action', 'my_action');
. That is what codex specifies should be done. Which means changing the handler function name tomy_action
from insertEmail. See: codex.wordpress.org/AJAX_in_Plugins