INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Ajax Call Returning 0 - using JQuery $.post. Don't know why. Need help.

Ajax Call Returning 0 - using JQuery $.post. Don't know why. Need help.

Ajax Call Returning 0 - using JQuery $.post. Don't know why. Need help.

(OP)
Hi all,

I'm building my first wordpress plugin on Subdomain of site (I only mention it because I don't think this is an xss issue). Am using Ajax with Jquery for functionality on Administrative Side (Backend, not Frontend); on admin panels.

However, Ajax keeps returning 0; this is in spite of me having 'die()' at end of the calling/handler function and using the correct Ajax 'Action' call (wp_ajax_ACTION).

It should return "DATA TO BE ECHOED!" according the my test handler function.

Full code below. All insight, constructive comments, and directions are welcome. Thanks!

The JQUERY... ('t-admin.js'):

CODE --> jquery

jQuery(document).ready(function($) {

     $('#p2_form1').submit(function() {
	var data = {
		action: "results_test"
	};
	try {
	$.post(ajaxurl, data, function(response) {
		// jQuery('#ajax_data').html(response);
		 alert ('Response is: ' + response);
		// this call should return "DATA TO BE ECHOED!"
		// alert (typeof response); // this returns 'string'; don't know why
		});
	} catch (err) {
		return err;
	}
	
		return false;
     });
    }); 

The PHP Calling/Handler File (Admin Panel Page 2)... ('t-page2.php'):

CODE --> php

<?php
    // protect page; make sure user can update opts
    if ( !current_user_can('manage_options') ) {
    	wp_die (__("You don't have permission to access this page.") );
    }
    ?>
    
    <div class="wrap">
      <?php screen_icon('options-general'); ?>
        <h2>
          <?php _e('Manage Page 2 Settings:'); ?>
        </h2>
        <p>Settings form here...
           	<form name="p2_form1" id="p2_form1" method="post" action="">
              <?php settings_fields('tp2_opts_groups'); ?>
             <p>input fields, radio buttons, blah blah</p>
              <input type="submit" id="test_submit" value="Test Submit Button" class="button-primary" />
             </form>
    
              <?php
    		  // error_reporting(E_ALL);
    		  // TESTING AJAX RESUTLS...
    		  	function my_action_callback() {
    				 echo ("DATA TO BE ECHOED!");
    				die(); 
    			  }
    		  // Keep getting 0. Why? Am using "die()" at end and wp_ajax_ACTION is correct.
    			  
    		  add_action( 'wp_ajax_results_test', 'my_action_callback');
    		  // add_action( 'wp_ajax_nopriv_results_test', 'my_action_callback');
    		  // NoPriv not necessary. This is on Admin Panels (Backend, NOT Frontend)
    		  ?>
              <p> data will appear here...</p>
              <div id="ajax_data">
              <!-- data to eventually appear here! -->
              </div>
              
    
    </div> 

Rest of Files should anyone need to take a look at entire code...


The Plugin File... ('test-plugin.php'):

CODE --> php

<?php
    defined( 'ABSPATH' ) OR exit;
    /*
    Plugin Name: Test Plugin
    Version: 1.0
    Author: WP Plugin Newbie
    Description: Building my first plugin.
    Version: 1.0
    License: Free
    */
    
    // protect page
    if ( !function_exists('add_action') ) {
    	echo ( "Sorry, this page doesn't do much when accessed directly" );
    	exit(0);
    }
    
    
    // main class to handle function calls
    class TestPluginCls {
    	public $version_num = '1.0';
    	
    	function TestPluginCls() {
    		// get constants
    		$this->TestPluginConstants();
    		// register db setup
    		register_activation_hook( __FILE__, array(&$this, 'setup_DB') );
    		// action
    		add_action( 'plugins_loaded', array(&$this, 'start_TestPlugin') );
    	}
    	
    	// set up db
    	function setup_DB() { 
    		// require
    		require_once ( dirname(__FILE__) . '/admin/t-dbsetup.php' );
    		// call db class
    		$this->TestPluginDbSetupCls = new TestPluginDbSetupCls();
    	} 
    	
    	// launch Test Plugin
    	function start_TestPlugin() {
    		if ( is_admin() ) {
    			// require
    			require_once ( dirname(__FILE__) . '/admin/t-admin.php' );
    			// setup Admin area
    			$this->TestPluginAdminAreaCls = new TestPluginAdminAreaCls();
    		} 
    	
    	}
    	
    	// define constants
    	function TestPluginConstants() {
    		define ( 'TestPlugin_FOLDER', plugin_basename(dirname(__FILE__)) );
    		define ( 'TestPlugin_URL', plugin_dir_url(__FILE__) );
    		define ( 'TestPlugin_PATH', plugin_dir_path(__FILE__) );
    	}
    	
    }
    
    global $TestPlugin;
    global $wpdb;
    $TestPlugin = new TestPluginCls();
    
    ?> 

Admin/Menu Building Class... ('t-admin.php'):

CODE --> php

<?php
    
     error_reporting(E_ALL);
    // ini_set('display_errors', '1');
    
    class TestPluginAdminAreaCls {
    	public $role = 'activate_plugins';
    		
    	function TestPluginAdminAreaCls() {
    		// register stuff
    		add_action( 'admin_menu', array(&$this, 'TestPluginMenu') );
    		add_action( 'admin_init', array(&$this, 'register_tplugin_options') );
    		// add_action( 'wp_ajax_get_tmps', 'my_action_cb'); // placing here produces error notice!
    		// add_action( 'admin_enqueue_scripts', array(&$this, 'tp_load_admin_scripts') );
    	
    	}
    	
    	// build menu
    	function TestPluginMenu() {
    	
    		$phsfx_home = add_menu_page( __('Test Plugin Admin Area'), __('Test Plugin'), $this->role, TestPlugin_FOLDER, array(&$this, 'output_page') );
    		
    		$phsfx_main = add_submenu_page( TestPlugin_FOLDER, __('Test Plugin Admin Area'), __('TP Main'), $this->role, TestPlugin_FOLDER, array(&$this, 'output_page') );
    		
    		$phsfx_p1 = add_submenu_page( TestPlugin_FOLDER, __('Test Plugin : Page 1'), __('TP Page 1'), $this->role, 'tp1', array(&$this, 'output_page') );
    		
    		$phsfx_p2 = add_submenu_page( TestPlugin_FOLDER, __('Test Plugin: Page 2'), __('TP Page 2'), $this->role, 'tp2', array(&$this, 'output_page') );
    		
    	
    	// only show admin scripts and dependencies on TP pages as needed
    		add_action( 'admin_print_scripts-' . $phsfx_home, array(&$this, 'tp_load_admin_scripts') );
    		add_action( 'admin_print_scripts-' . $phsfx_main, array(&$this, 'tp_load_admin_scripts') );
    		add_action( 'admin_print_scripts-' . $phsfx_p1, array(&$this, 'tp_load_admin_scripts') );
    		add_action( 'admin_print_scripts-' . $phsfx_p2, array(&$this, 'tp_load_admin_scripts') );
    		
    	}
    	
    	function register_tplugin_options() {
    		// add_action( 'wp_ajax_get_tmps', 'my_action_cb'); // placing here throws crazy error notice!
    		register_setting( 'tp1_opts_groups', 'tp1_opts' );
    		register_setting( 'tp2_opts_groups', 'tp2_opts');
    	}
    	
    	// output proper page
    	function output_page() {
    		switch ($_GET['page']) {
    			case "tp1" :
    				include_once( dirname(__FILE__) . '/t-page1.php');
    				break;
    			case "tp2" :
    				include_once( dirname(__FILE__) . '/t-page2.php');
    				break;
    			default :
    				include_once( dirname(__FILE__) . '/t-main.php');
    				break;
    		}
    	}
    	
    	// scripts/css
    	function tp_load_admin_scripts() {
    	// load JS
    		wp_enqueue_script ( array('jquery', 'farbtastic', 'media-upload', 'postbox', 'thickbox') );
    		wp_enqueue_script ( 't-admin-js', TestPlugin_URL.'js/t-admin.js', array('jquery'), '1.0' );
    	// localize???
    		//wp_localize_script ( 't-admin-js', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); // don't know if necessary
    	
    	// load CSS
    	 	wp_enqueue_style ( array('thickbox', 'farbtastic') );
    		wp_enqueue_style ( 't-admin-css', TestPlugin_URL.'css/t-admin.css', array(), '1.0', 'screen' );
    	
    	}
    
    }
    
    
    ?> 

DB Setup Class... ('t-dbsetup.php'):

CODE --> php

<?php
    
    class TestPluginDbSetupCls {
    
    	function TestPluginDbSetupCls() {
    		global $wpdb;
    		
    		// insert info into DB...
    		// Tested. All code here works.
    	}
    	
    }
    ?> 

Admin Panel Main Page... ('t-main.php'):

CODE --> php

<?php
    // protect page
    if ( !current_user_can('manage_options') ) {
    	wp_die (__("You don't have permission to access this page.") );
    }
    ?>
    
    <div class="wrap">
    	<h2>Test Plugin</h2>
      <p><b>Manage Page 1:</b></p>
    	<blockquote class="section">
    	  <p><a href="#">Link to page 1 settings</a> -- Here is where you can...</p>
      </blockquote>
    	
    	<p><b>Manage Page 2:</b></p>
    	<blockquote class="section">
    	  <p><a href="#">Link to page 2 settings</a> -- Here is where you can...</p>
      </blockquote>
    
    </div> 

Admin Panel Page 1... ('t-page1.php'):

CODE

<?php
    // protect page; make sure user can update opts
    if ( !current_user_can('manage_options') ) {
    	wp_die (__("You don't have permission to access this page.") );
    }
    ?>
    
    <div class="wrap">
      <?php screen_icon('options-general'); ?>
        <h2>
          <?php _e('Manage Page 1 Settings:'); ?>
        </h2>
        <p>Settings form here...</p>
              <form name="p1_form1" id="p1_form1" method="post" action="">
              <?php settings_fields('tp1_opts_groups'); ?>
              <p>input fields, radio buttons, blah blah</p>
              <p> </p>
              </form>
    </div> 

RE: Ajax Call Returning 0 - using JQuery $.post. Don't know why. Need help.

I suspect that the reason is that there is no reason for wordpress to have loaded up the page template in response to an admin-ajax request. so t-page2 is most probably not loaded into memory. given that there is no fatal error, I suspect that not even the ajax hook is being registered.

so let's start from scratch and set this up as a plugin.

1. save this in the plugins folder under whatever name you want (*.php)
2. put this code into the file you've just created

CODE

<?php
/*
Plugin Name: My Plugin Name
Description: Tek-Tips sample plugin
Version: 0.1.0
Author: 
License: GPL2
*/

class myPlugin{
	
	private $myAction = 'results_test';
	
	public function __construct(){
		$this->registerHooks();	
	}
	
	public function registerHook(){
		/*
		 * we need an admin-footer hook for the javascript
		 * and
		 * an ajax handler
		 */
		
		/*
		 * this is to output the javascript
		 */
		add_action( 		'admin_footer',  		// fire this when we get to the admin footer 
							array(				
									&$this, 		// tells the hook to use this object
									'sendJs'		// tells the hook to use the sendJS method
								)
		);
		
		add_action(			'wp_ajax_' . $this->myAction, 
							array(
									&$this,
									'process'
								)
		);
	}
	
	/*
	 * this is just an internal method that breaks out of php
	 * and inserts some javascript
	 */
	public function sendJs(){
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
	$('#p2_form1').submit(function( e ) {
		console.log('form has been submitted');
		e.preventDefault();	
		var data = {
			action: "<?php echo $this->myAction;?>"
		};
		jQuery.ajax({
				data:	data,
				dataType: 'json',
				type: 'POST',
				url: ajaxurl,
				complete: function (data){
					console.log('result data: ' , data);
				}
		});
	});
}); 
</script>
<?php
	}
	
	/*
	 * 		this gets called by the admin ajax
	 */
	public function process(){
		
		/*
		 * we can send anything back 
		 * 
		 */
		$array = array(
						'result' => 'ok',
						'data' 	=> "Hello World"
		);
		
		echo json_encode($array); 	//the json_encode is important so that jquery reads it ok
		die; //should not be necessary for wordpress
	}	
}

//start the engine up
new myPlugin;
?> 

then fire up the admin panel and enable this plugin.

notes: this plugin will then fire on every admin page. but this is not massively problematic provided that the if p2_form is only used on one page.

If this is problematic then add the following line to the start of the sendJS method

CODE

if ( 't-page1.php' !== $GLOBALS['pagenow'] ) return; 

RE: Ajax Call Returning 0 - using JQuery $.post. Don't know why. Need help.

(OP)
Thank JPadie for the detailed help. I really appreciate it.

Your suspicions were correct. The ajax hook wasn't being registered.

Turns out I had to move the "handler" function (my_action_callback) from the "t-page2.php" page, and place it inside the main class as a method. I then had to move the "add_action" for the WP_Ajax hook and call it outside the main class.

Sheeesh! I gotta read up some more about classes :)

Thanks again!

RE: Ajax Call Returning 0 - using JQuery $.post. Don't know why. Need help.

it's not about classes, really.

the nature of ajax with wordpress is that, when the ajax requests hits wordpress, all that is loaded is the bare minimum to service the request. no page level resources are loaded. so by putting the hook and the callback in the page wordpress will never even see it. if the hook had been registered then it would have called a fatal error as php would not have been able to locate the function.

so it's more about understanding what resources are loaded by wordpress in each circumstances. this is distinctly non-trivial so it's best, imo, to register admin-side stuff as a plugin, and choose the action hooks to be early in the load process; and then you have more flexibility on the client side. shove stuff in the functions.php file or do as a plugin. but remember, with functions.php, ajax calls will not always load functions.php so you'd still have to register the ajax hook somewhere else.

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close