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!.


<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  
// creating Ajax call for WordPress  
add_action( 'wp_ajax_nopriv_MyAjaxFunction', 'MyAjaxFunction' );  
add_action( 'wp_ajax_MyAjaxFunction', 'MyAjaxFunction' ); 


jQuery(document).ready(function() {  

    var GreetingAll = jQuery("#GreetingAll").val();  

            type: 'POST',  
            url: '/wp-admin/admin-ajax.php',  
            data: {  
                action: 'MyAjaxFunction',  
                GreetingAll: GreetingAll,  
            success: function(data, textStatus, XMLHttpRequest){  
                alert('Success: ' + data);
            error: function(MLHttpRequest, textStatus, 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!


1st) Add another dependency: array( 'json2', 'jquery' );.

2nd) Dig into and read about wp-localize-script() in Codex. It allows you to send data from PHP to javascript via an javascript var, set in PHP (as 2nd arg for wp_localize_script()).

  • Thanks for your answer! I have updated wp_enqueue_script( 'ajax-implementation.js', get_stylesheet_directory_uri() . "/scripts/ajax-implementation.js", array( 'json2', 'jquery' ) ). I have read about wp-localize-script, but not sure how you are suggesting using it in this case. With just adding json2, I am still getting -1. – Mark Rummel Jul 24 '12 at 15:07
  • Please read some of the answers in detail - you'll see how to pass vars from php to js. and proper fire the result. – kaiser Jul 24 '12 at 16:36

Just add at the end of your ajax function (in the PHP file) die(); and after your echo "your output" it will get rid of that 0.

(Sorry if late I just found this question)


In your ajax call, Just

echo $results;

Then do



echo $results;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.