I am trying to figure out how to use jQuery $.ajax()
for a project. I setup this test using what I learned from TutsPlus.com. Everything seems to be working correctly except I am getting a -1
returned. So I get an alert with Success: -1
and #test-div1
is populated with -1
, instead of Hello Everyone!
.
My HTML:
<input type="hidden" name="GreetingAll" id="GreetingAll" value="Hello Everyone!" />
<input class="btn" type="submit" id="PleasePushMe" />
<div id="test-div1"></div>
In functions.php:
function add_myjavascript(){
wp_enqueue_script( 'ajax-implementation.js', get_stylesheet_directory_uri() . "/scripts/ajax-implementation.js", array( 'jquery' ) );
}
add_action( 'init', 'add_myjavascript' );
function MyAjaxFunction(){
//get the data from ajax() call
$GreetingAll = $_POST['GreetingAll'];
$results = "<h2>".$GreetingAll."</h2>";
// Return the String
die($results);
}
// creating Ajax call for WordPress
add_action( 'wp_ajax_nopriv_MyAjaxFunction', 'MyAjaxFunction' );
add_action( 'wp_ajax_MyAjaxFunction', 'MyAjaxFunction' );
ajax-implementation.js:
jQuery(document).ready(function() {
var GreetingAll = jQuery("#GreetingAll").val();
jQuery("#PleasePushMe").click(function(){
jQuery.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: {
action: 'MyAjaxFunction',
GreetingAll: GreetingAll,
},
success: function(data, textStatus, XMLHttpRequest){
alert('Success: ' + data);
jQuery("#test-div1").html('');
jQuery("#test-div1").append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
My only modification is changing get_bloginfo('template_directory')
to get_stylesheet_directory_uri()
, because I am using a child theme.
Any thoughts on how I can get this working? Thanks!