I’m trying to get data from php function in a WordPress Plugin using AJAX. I need to add that these hooks are totally confusing to me… I’m playing around with example from https://codex.wordpress.org/AJAX_in_Plugins and I changed it a little to alert some data on a button click.
In my plugin:
function my_enqueue($hook) {
/**if( 'index.php' != $hook ) {
// Only applies to dashboard panel
return;
}*/
wp_enqueue_script( 'ajax-script', plugins_url( 'js/formAdd_.js', __FILE__ ), array('jquery') );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ); );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
// Same handler function...
add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb;
$names = array();
while ( bp_group_members() ) : bp_group_the_member();
array_push($names, bp_group_member_name() );
endwhile;
echo json_encode($names);
die();
}
And in my js file:
jQuery(document).ready(function($) {
//ajax example
jQuery('.ajaxTrigger').live('click',function(){
var data = {
'action': 'my_action',
'whatever': ajax_object.we_value // We pass php values differently!
};
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(ajax_object.ajax_url, function(response) {
alert(response[0]);
});
});
And the button somewhere in my plugin:
<button type="button" class="ajaxTrigger">Click Me!</button>
I’m not sure what goes wrong there, technically I should be able to call the function with a simple button click or is the php function supposed to be triggered first?
Also the error in the console says POST wp-admin/admin-ajax.php 500 (Internal Server Error)
Update:
Removed some unnecessary code from JavaScript and alert is there however it just alerts 0, so it means that the while loop in my php function is not returning a proper array I think.
jQuery('.ajaxTrigger').live('click',function(){
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(ajax_object.ajax_url, function(response) {
alert(response[0]);
});
});
The entire plugin php code
function my_plugin_init() {
require_once( dirname( __FILE__ ) . '/getGroupExt.php' );
/* If you have code that does not need BuddyPress to run, then add it here. */
if ( !defined( 'ABSPATH' ) ) exit;
wp_enqueue_script( 'ajax-script', plugins_url( 'js/formAdd_.js', __FILE__ ), array('jquery') );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' )) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
// Same handler function...
add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_enqueue($hook) {
/**if( 'index.php' != $hook ) {
// Only applies to dashboard panel
return;
}*/
function my_action_callback() {
global $wpdb;
$names = array();
if ( bp_group_has_members( 'group_id='.bp_get_group_id().'&exclude_admins_mods=false' ) ) :
while ( bp_group_members() ) : bp_group_the_member();
//$name = bp_get_group_member_name();
$name = bp_group_member_name() ;
array_push($names, $name);
endwhile;
echo json_encode($names);
die();
endif;
}
/**
* The class_exists() check is recommended, to prevent problems during upgrade
* or when the Groups component is disabled
*/
if ( class_exists( 'BP_Group_Extension' ) ) :
class Group_Extension_Example_1 extends BP_Group_Extension {
/**
* Your __construct() method will contain configuration options for
* your extension, and will pass them to parent::init()
*/
function __construct() {
$args = array(
'slug' => 'group-extension-example-1',
'name' => 'Group Extension Example 1',
);
parent::init( $args );
}
//from ajax example
/**
* display() contains the markup that will be displayed on the main
* plugin tab
*/
function display() {
//if admin
$user_id=get_current_user_id();
$group_id = bp_get_group_id();
if (groups_is_user_admin( $user_id, $group_id )) {
echo 'There are no tasks! - Set your tasks for this group';
?>
<div class="input_fields_wrap">
<button class="add_field_button">Add Another Task</button>
<p><input type="text" name="mytext[]"></p>
<button type="button" class="ajaxTrigger">Click Me!</button>
<?php
$has_members_str = "group_id=" . $group_id;
if ( bp_group_has_members( $has_members_str ) )
: ?>
<select name ="member">
<?php while ( bp_group_members() ) : bp_group_the_member(); ?>
<option value="<?php bp_group_member_name() ?>"> <?php bp_group_member_name() ?> </option>
<?php endwhile; ?>
</select>
<?php else: ?>
<h2>you're not part of any groups.</h2>
<?php endif;?>
<input id="enddate" name="enddate" min="2014-12-01" max="2019-01-01" type="date">
</div> <br />
<?php
}
else {
echo "You're not an admin!";
}
}
/**
* settings_screen() is the catch-all method for displaying the content
* of the edit, create, and Dashboard admin panels
*/
function settings_screen( $group_id ) {
$setting = groups_get_groupmeta( $group_id, 'group_extension_example_1_setting' );
?>
Save your plugin setting here: <input type="text" name="group_extension_example_1_setting" value="<?php echo esc_attr( $setting ) ?>" />
<?php
}
/**
* settings_sceren_save() contains the catch-all logic for saving
* settings from the edit, create, and Dashboard admin panels
*/
function settings_screen_save( $group_id ) {
$setting = '';
if ( isset( $_POST['group_extension_example_1_setting'] ) ) {
$setting = $_POST['group_extension_example_1_setting'];
}
groups_update_groupmeta( $group_id, 'group_extension_example_1_setting', $setting );
}
}
bp_register_group_extension( 'Group_Extension_Example_1' );
endif; // if ( class_exists( 'BP_Group_Extension' ) )
}
add_action( 'bp_include', 'my_plugin_init' );
?>
Thanks in advance.
If you want to use
ajax_object.we_value
, you’ll have to create that variable withwp_localize_script()
:In your JS, use
ajax_object.we_value
and post it toadmin-ajax.php
aswhatever
In your AJAX callback, catch and use the
whatever
value, and send the response back: