Declaring and using global variables in a custom admin menu item - php

I'm working on a custom review system. In this project in need to have and ID passed from a callback function which is declared below:
add_action( 'wp_ajax_edit_review', 'edit_review_callback' );
function edit_review_callback() {
check_ajax_referer( 'edit-review-function', 'security' );
$GLOBALS['review_edit_id'] = $_POST['table_id'];
echo $GLOBALS['review_edit_id'];
die();
}
That function is called like this:
$(".edit_review").click(function() {
//Select the right id for selecting right row
var tr = $(this).closest('tr');
var td = tr.find('td:eq(0)').text();
//Create data to send withs security nonce
var data = {
action: 'edit_review',
security: '<?php echo $ajax_nonce_edit; ?>',
table_id: td
};
//Send ajax-request
$.post(ajaxurl, data, function(response) {
alert( 'Response: ' + response );
});
var url = "<?= get_site_url() . '/wp-admin/admin.php?page=sub_menu_item_two_review'?>";
$(location).attr('href',url);
});
I want to set these global variables to use them in my custom menu item.
Which is declared like this:
add_submenu_page(
'review_page_slug',
'review_menu_page',
'Edit review',
'manage_options',
'sub_menu_item_two_review',
'edit_review_render'
);
Some where in here i want to use the variable:
function edit_review_render() {}
Ways I have tried to declare global variables;
global $review_edit_id; $review_edit_id = value;
$GLOBALS['review_edit_id'] = $_POST['table_id']; //As visible in the code below;
Ways I have tried to read variables:
global $review_edit_id; var_dump($review_edit_id); //Same as using the databas with global $wpdb;
var_dump($GLOBALS['review_edit_id']);
echo $GLOBALS['review_edit_id'];
I'm new to wordpress and have been working with it for about 4 weeks by now. I think its fun but I've been stuck on this part since the day before yesterday. Any help woud be much apriciated(and sorry for the big amount of code.).

Related

Ajax call to PHP function - saving picture gallery from settings page in Wordpress

Can someone show me a good example of how to call a PHP function with Ajax? I'm trying to save an image gallery (with dynamic number of images) to database in the admin settings section. The below code is incomplete or maybe with some errors. Please show me a good example or a better way:
<button type="button" class="btn btn-primary" onclick="jsAddSettingsFields()">Save Changes</button>
function jsAddSettingsFields(){
var elements = document.getElementsByTagName("img");
var urlsdata = new Array();
for (var i = 0, element; element = elements[i++];) {
if (elements[i].id == "idGalPic") {
urlsdata[i] = elements[i].src;
// now we have all image urls in array, now need to
// call add_settings_fields
var data = {
action: 'php_addsettingsfields',
p_urls: urlsdata //I think i need to JSON this
};
jQuery.post( "", function( data ) );
}
}
}//end of js function
<?php
add_action( 'wp_ajax_update_options', 'php_addsettingsfields_callback' );
add_action( 'wp_ajax_nopriv_update_options', 'php_addsettingsfields_callback' );
function php_addsettingsfields_callback() {
$pic_urls = $_POST['p_urls']; // De-JSON-fy this variable
foreach ($pic_urls as &$url) {
add_settings_field($url);
}
add_settings_field(
'pic_url_id', // ID - slug name of field
'', // Title
array( $this, 'pic_gal_callback' ), // Callback
'TestPlugin', // Page
'setting_section_id' // Section ID - slug name of page
);
public function pic_gal_callback() {
<input type="hidden" id="idPic" name="idPic" value=$url />
}
// after all hidden fields(with gallery pic urls) are added to setting section submit
// the page and save the gallery urls to database
Here take a look at a working ajax example from one of my plugins.
Javascript Part:
//setting click event on button click to fire a function
$('#YourButtonIdHere').click(function () {
YourFunctionNameHere();
});
//function to execute
function YourFunctionNameHere() {
//formdata variable consists of
//action: this is ajax action name for WordPress which we define in PHP with a callback function with same name. See in PHP code part.
//$('#YourFormIDHere').serialize(); //this gets content from form and serialize it.
var frm_data = "action=your_action_name_here&" + $('#YourFormIDHere').serialize();
$.ajax({
type: "POST",
url: ajaxurl, // since WordPress version 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
data: frm_data,
cache: false,
success: function(data, textStatus, jqXHR) {
//do stuff here in case of success
},
error: function(jqXHR, textStatus, errorThrown) {
//do stuff here in case of error
}
});
}
PHP Part:
//here wp_ajax is the required prefix for your custom actions
//first parameter is action name with wp_ajax prefix
//second parameter is callback function to execute with same name as your action
//for example if your action name is wp_ajax_save_settings then your callback will be save_settings
add_action( 'wp_ajax_your_action_name_here', 'your_action_name_here' );
function your_action_name_here() {
global $wpdb; // this is how you get access to the database
//do stuff here and echo response
echo "ajax call success";
wp_die(); // this is required to terminate immediately and return a proper response
}

Get PHP values in AJAX to replace input field values

I've created a Custom Post Type in Wordpress called Location/Tour and another one called Itinerary. In my CPT Itinerary, I have some ACF custom fields one of them is a repeater field that has subfields (Relationship field for the CPT Location/Tour, Title field, Description field).
I've created a button that should trigger an AJAX script which job is to get the values from the CPT Location/Tour(Title and Description) and
put them in my input subfields(Title and Description) in my CPT Itinerary.
I've created a PHP function that gets the values from the CPT Location/Tour and now I'm trying to run the PHP function using AJAX.
I was able to get the AJAX working and I get the values in my console log under ResponseText.
Now the part I'm struggling with. I need to set each value as a separate variable in JS so that I can replace the input field values with the new ones but unfortunately I don't know how.
I've tried almost everything and I think that I'm close to the answer but I'm missing something. :(
Here is my post-value-loader.php
<?php
// LOAD DEFAULT VALUES FROM DEFAULT TOUR
add_action('wp_ajax_post_loader', 'post_loader');
function post_loader($field) {
$post_id = $_POST["post_id"];
$args = array(
'p' => $post_id,
'numberposts'=> -1, // Fetch all posts...
'post_type'=> 'location_tour', // from the 'location_tour' CPT...
);
$location = new WP_Query( $args );
if ( $location->have_posts() ) : while ( $location->have_posts() ) : $location->the_post();
$title = the_field('title'); //The Title field value that we need
$description = the_field('description'); //The Description field value that we need
wp_reset_postdata();
?>
<?php endwhile; endif; ?>
<?php add_action('acf/prepare_field/name=default_tour', 'post_loader'); ?>
<?php }
// BUTTON TO RUN AJAX
function my_acf_prepare_field($field) {
echo '<div class="acf-field"><button type="submit" id="data_fetch" class="button acf-load-default-tour-values">Load default value</button></div>';
return $field;
}
add_action('acf/prepare_field/name=default_tour', 'my_acf_prepare_field');
// ADD SCRIPT TO WORDPRESS ADMIN AJAX
function js_data_fetch() {
wp_enqueue_script ("ajax-data-fetch", get_stylesheet_directory_uri() . "/inc/assets/js/data-fetch.js", array('jquery'));
//the_ajax_script will use to print admin-ajaxurl in data-fetch.js
wp_localize_script('ajax-data-fetch', 'the_ajax_script', array('ajaxurl' =>admin_url('admin-ajax.php')));
}
add_action("admin_enqueue_scripts", "js_data_fetch");
?>
And here is my data-fetch.js (Note: I'm not a JS guy :( )
jQuery(document).on( 'click', '#data_fetch', function( dohvati ){
dohvati.preventDefault();
var post_id = jQuery('.acf-row .selection .values ul li span').data('id'); // This takes the post ID from the selected Post(Location/Tour) in the Relationship field
jQuery.ajax({
url: the_ajax_script.ajaxurl, //The URL that we set for the wordpress admin-ajax.php
type: "POST",
dataType: 'json',
data: {
action: 'post_loader', // This is the name of the php function
post_id: post_id,
},
success: function(data){
console.log(data)
},
error: function(error){
console.log(error)
},
});
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeabc041c8a").val(title); //This is replacing the title field - but the variables are missing
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeab8f41c89").val(description); //This is replacing the description field - but the variables are missing
});
Also here are two images from the CPT Itinerary editor (https://imgur.com/kFImdpe) with the fields and my console log (https://imgur.com/wwxKXQP). Hope that this helps.
You have to return the data as JSON from post_loader function. I've cleaned up a little, but still, it's a mess.
// LOAD DEFAULT VALUES FROM DEFAULT TOUR
add_action('wp_ajax_post_loader', 'post_loader');
function post_loader() {
$post_id = $_POST["post_id"];
$args = array(
'p' => $post_id,
'numberposts'=> -1, // Fetch all posts...
'post_type'=> 'location_tour', // from the 'location_tour' CPT...
);
$location = new WP_Query( $args );
if ( $location->have_posts() ) :
while ( $location->have_posts() ) :
$location->the_post();
$title = the_field('title');
$description = the_field('description');
// You have to return data as json
wp_send_json([
'title' => $title,
'description' => $description
]);
//wp_reset_postdata();
endwhile;
endif;
// Why do you need this inside this function?
// add_action('acf/prepare_field/name=default_tour', 'post_loader');
}
JS
jQuery(document).on( 'click', '#data_fetch', function( dohvati ){
dohvati.preventDefault();
var post_id = jQuery('.acf-row .selection .values ul li span').data('id'); // This takes the post ID from the selected Post(Location/Tour) in the Relationship field
jQuery.ajax({
url: the_ajax_script.ajaxurl, //The URL that we set for the wordpress admin-ajax.php
type: "POST",
dataType: 'json',
data: {
action: 'post_loader', // This is the name of the php function
post_id: post_id,
},
success: function(data){
console.log(data)
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeabc041c8a").val(data.title); //This is replacing the title field - but the variables are missing
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeab8f41c89").val(data.description); //This is replacing the description field - but the variables are missing
},
error: function(error){
console.log(error)
},
});
});

Onclick Link POST to REST

I'm making sure I am going about this the right way because WooCommerce kinda complicates things. First I'll explain what I am looking for. I'm wanting it so when an admin clicks a custom button I created in the WooCommerce orders page that it shows them the tracking number for a specific order. I have that up and running just fine. Now what I would also like to do is to make a call to my api with their username and post it to my log with the admin username along with the tracking number they accessed. However I'm running into a couple issues, some of which I haven't encountered yet, but feel as though they could be a problem. So I have the link in one function that loops through each order to display the tracking button, and the css/ajax in another function for being posted in the head section. So here are some issues:
1.) How can I make it so that I only need one instance of jQuery? I don't want it to flood the source code with multiple instances.
2.) I thought maybe just posting it once in the head section would be fine, but if it's not in the link button function then how will the jQuery get the correct value if the variable is different for each order id since it would no longer be looping through each instance with the jQuery?
3.) How could I accomplish this call from another host so I do not need to upload my API to each domain?
Here is the code I have so far, please tell me if there is a better way to go about this task. Thank you in advance.
add_action( 'woocommerce_admin_order_actions_end', 'add_custom_order_actions_button', 100, 1 );
function add_custom_order_actions_button( $order ) {
// Username
$user_info = get_userdata($order->user_id);
// Tracking
$tracking_number = get_post_meta( $order->get_id(), '_disquy_tracking_number', true );
if( empty($tracking_number) ) return;
// Prepare the button data
$url = esc_url('https://track.disquy.com/'.$tracking_number.'?');
$name = esc_attr( __('Tracking', 'woocommerce' ) );
$class = esc_attr( 'tracking' );
printf( '<a class="button wc-action-button wc-action-button-%s %s" href="%s" title="%s" id="apicall">%s</a>', $class, $class, $url, $name, $name );
}
add_action( 'admin_head', 'add_custom_order_actions_button_css' );
function add_custom_order_actions_button_css() {
echo '<script type="text/javascript">
$("#apicall").click(function(event){
event.preventDefault();
$.post("adminlog.php", {username : ' . $user_info . ', tracking : ' . $tracking_number . '}, function(response){
alert(response);
});
});
</script>
<style>.wc-action-button-tracking::after { font-family: woocommerce !important; content: "\e01a" !important; }</style>
}
Actually, you don't need jQuery at all! It's been awhile since I've worked with PHP based CMS's, but here's an alternative example to what you could do. Just check the PHP syntax to make sure it's correct. No jQuery. Pure vanilla JS. Uses native Fetch API to handle AJAX request.
add_action( 'woocommerce_admin_order_actions_end', 'add_custom_order_actions_button', 100, 1 );
function add_custom_order_actions_button( $order ) {
// UserID
$user_id = get_userdata($order->user_id);
// Tracking Data
$tracking_data = get_post_meta($order->get_id(), '_disquy_tracking_number', true );
if(empty($tracking_data)) return;
$base_url = 'https://track.disquy.com';
$url = esc_url(.$base_url.'/'.$tracking_data.'?');
$name = esc_attr( __('Tracking', 'woocommerce' ) );
$class = esc_attr( 'tracking' );
printf('<a class="button wc-action-button wc-action-button-
%s %s" href="%s" title="%s" id="apicall">%s</a>',
$class, $class, $url, $name, $name );
}
add_action( 'admin_head', 'add_custom_order_actions_button_css' );
function add_custom_order_actions_button_css() {
echo '<script type="text/javascript">
const elem = document.getElementById('#apicall')
elem.addEventListener('click', postUserTransaction)
const postUserTransaction = (e) => {
e.preventDefault();
const postData (e) => {
event.preventDefault();
const tittle = elem.title;
const body = document.body.value;
return fetch('adminlog.php', {
method: 'POST',
headers : new Headers({
"username":".$user_id.",
"tracking":".$tracking_data.'
})
})
.then(res => res.json())
.then(data => data)
.then(data => {
console.log(data)
alert(data)
return data
})
.catch(err => new Error(err))
}
}
</script>
<style>.wc-action-button-tracking::after { font-family: woocommerce !important; content: "\e01a" !important; }</style>
}
By using the addEventListener method instead of defining the onclick method inline your HTML. You should be able to write all your JS scripts in a separate folder, then import them using hooks. Again, it's been awhile though. If you're looking for dynamic rendering of DOM variables, jQuery wont work. It only works with a rendered DOM. Vanilla JS can take care of this for you, but you'll need aditional configs. I honestly think there has to be hooks included using PHP for inject DOM elements on update. Then simple write eventListeners for changes in the DOM, then make necessary updates.
As mentioned before, include your scripts files elsewhere, then hook them into the page via PHP and your WooCommerce API for doing so.
Cheers!
EDIT:
You need to modify the fetch and promise chain to POST you PHP script, then edit the then block containing the alert to add the response data to the DB. Here is another example using fetch to POST with PHP. I don't know what vars and hooks you have to work with to make the final DB update using your Res data. That's something you should have.
fetch("http://www.example.org/submit.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: "key=val&key2=val2"
})
.then(res => res.json()),
.then(res => {
if (res.ok) {
alert("Perfect! Your settings are saved.");
} else if (res.status == 401) {
alert("Oops! You are not authorized.");
}
}, (e) => {
alert("Error submitting form!");
});

Wordpress AJAX not calling PHP function

I've tried a bunch of different things but I just cannot get AJAX with Wordpress to work. I clearly don't get something but I do not know what it is. The PHP function works fine since I have tested it, it just seemingly isnt getting through to the JS. The idea is that when someone clicks the #subscribe-btn div its updates that users meta, nothing overly sophisticated. Any help on why this isnt working would be great.
This is in my theme's functions.php:
function add_admin_ajax()
{
wp_localize_script( 'add_ajax', 'functionAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'add_ajax', get_template_directory_uri().'/assets/js/onLoad.js', 'jquery', true);
}
add_action('template_redirect', 'add_admin_ajax');
add_action( 'wp_ajax_subscribe_cat', 'subscribe_cat' );
add_action( 'wp_ajax_nopriv_subscribe_cat', 'subscribe_cat' );
function subscribe_cat()
{
global $current_user;
if(is_user_logged_in())
{
get_currentuserinfo();
$userid = $current_user->ID;
$catsub = get_category(get_query_var('cat'));
$cat_id = $catsub->cat_ID;
$subs = get_user_meta($userid, 'user_subscriptions', true);
if(empty($subs))
{
$subs = array();
}
if(!in_array($cat_id, $subs))
{
$subs[] = $cat_id;
update_user_meta($userid, 'user_subscriptions', $subs);
//echo json_encode($subs);
}
}
die();
}
And then the jQuery:
$(document).on("click", "#subscribe-btn", function (e) {
//e.preventDefault();
$('#subscribe-btn').fadeOut(300);
$.ajax({
url: ajaxurl,
data: {action: "subscribe_cat"},
success: function() {
alert("Yay!")
},
error: function() {
alert("BOo!")
}
}); // end ajax call
});
I'm not getting either the success or error message. The div does fade out though that is something i guess. Any help here? Thanks!
EDIT:
I just changed the action identifier in add_action from subscribe to subscribe_cat and changed the ajax url from functionAjax.ajaxurl to simply ajaxurl. Now its responding. However I get the success alert twice, which I do not understand, and it doesn't seem its actually triggering the PHP function, or at least not properly, since I'm not getting the results I get when I simply call the function in PHP whithout ajax. Any ideas here?
One thing for sure you need to do is change the way your action is setup in the WordPress themes functions.php file.
I think this is an issue: wp_ajax_subscribe
This:
add_action( 'wp_ajax_subscribe', 'subscribe_cat' );
add_action( 'wp_ajax_nopriv_subscribe', 'subscribe_cat' );
should be:
add_action( 'wp_ajax_subscribe_cat', 'subscribe_cat' );
add_action( 'wp_ajax_nopriv_subscribe_cat', 'subscribe_cat' );
The action you set in your javascript needs to match the ending of the first parameter in your wordpress add_action call.
The WordPress documentation
You should pass page info such as query_var as "data" with your ajax function.
frontend page
<?php
$catsub = get_category(get_query_var('cat'));
$cat_id = $catsub->cat_ID;
?>
<script>
$(document).on("click", "#subscribe-btn", function (e) {
e.preventDefault();
$('#subscribe-btn').fadeOut(300);
$.ajax({
url: ajaxurl,
data: {
action: "subscribe_cat",
catid: "<?php echo $cat_id;?>"
},
success: function(response) {
console.log(response);
},
error: function() {
alert("BOo!")
}
}); // end ajax call
});
</script>
Also in your ajax function you had a condition that will always evaluate to false.
functions.php
add_action( 'wp_ajax_subscribe_cat', 'subscribe_cat' );
add_action( 'wp_ajax_nopriv_subscribe_cat', 'subscribe_cat' );
function subscribe_cat(){
//changed here!!
$cat_id = $_POST['catid'];
if(!$cat_id){
echo 'cat_id is missing';
exit;
} elseif(!is_user_logged_in()) {
echo 'Not logged in!';
exit;
}
$userid = get_current_user_id();
$subs = get_user_meta($userid, 'user_subscriptions', true);
if(empty($subs))
$subs = array();
$subs[] = $cat_id;
update_user_meta($userid, 'user_subscriptions', $subs);
echo json_encode($subs);
exit;
}

Wordpress: how to call a plugin function with an ajax call?

I'm writing a Wordpress MU plugin, it includes a link with each post and I want to use ajax to call one of the plugin functions when the user clicks on this link, and then dynamically update the link-text with output from that function.
I'm stuck with the ajax query. I've got this complicated, clearly hack-ish, way to do it, but it is not quite working. What is the 'correct' or 'wordpress' way to include ajax functionality in a plugin?
(My current hack code is below. When I click the generate link I don't get the same output I get in the wp page as when I go directly to sample-ajax.php in my browser.)
I've got my code[1] set up as follows:
mu-plugins/sample.php:
<?php
/*
Plugin Name: Sample Plugin
*/
if (!class_exists("SamplePlugin")) {
class SamplePlugin {
function SamplePlugin() {}
function addHeaderCode() {
echo '<link type="text/css" rel="stylesheet" href="'.get_bloginfo('wpurl').
'/wp-content/mu-plugins/sample/sample.css" />\n';
wp_enqueue_script('sample-ajax', get_bloginfo('wpurl') .
'/wp-content/mu-plugins/sample/sample-ajax.js.php',
array('jquery'), '1.0');
}
// adds the link to post content.
function addLink($content = '') {
$content .= "<span class='foobar clicked'><a href='#'>click</a></span>";
return $content;
}
function doAjax() { //
echo "<a href='#'>AJAX!</a>";
}
}
}
if (class_exists("SamplePlugin")) {
$sample_plugin = new SamplePlugin();
}
if (isset($sample_plugin)) {
add_action('wp_head',array(&$sample_plugin,'addHeaderCode'),1);
add_filter('the_content', array(&$sample_plugin, 'addLink'));
}
mu-plugins/sample/sample-ajax.js.php:
<?php
if (!function_exists('add_action')) {
require_once("../../../wp-config.php");
}
?>
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
var aref = this;
jQuery(this).toggleClass('clicked');
jQuery.ajax({
url: "http://mysite/wp-content/mu-plugins/sample/sample-ajax.php",
success: function(value) {
jQuery(aref).html(value);
}
});
});
});
mu-plugins/sample/sample-ajax.php:
<?php
if (!function_exists('add_action')) {
require_once("../../../wp-config.php");
}
if (isset($sample_plugin)) {
$sample_plugin->doAjax();
} else {
echo "unset";
}
?>
[1] Note: The following tutorial got me this far, but I'm stumped at this point.
http://www.devlounge.net/articles/using-ajax-with-your-wordpress-plugin
TheDeadMedic is not quite right. WordPress has built in AJAX capabilities. Send your ajax request to /wp-admin/admin-ajax.php using POST with the argument 'action':
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
jQuery(this).toggleClass('clicked');
jQuery.ajax({
type:'POST',
data:{action:'my_unique_action'},
url: "http://mysite/wp-admin/admin-ajax.php",
success: function(value) {
jQuery(this).html(value);
}
});
});
});
Then hook it in the plugin like this if you only want it to work for logged in users:
add_action('wp_ajax_my_unique_action',array($sample_plugin,'doAjax'));
or hook it like this to work only for non-logged in users:
add_action('wp_ajax_nopriv_my_unique_action',array($sample_plugin,'doAjax'));
Use both if you want it to work for everybody.
admin-ajax.php uses some action names already, so make sure you look through the file and don't use the same action names, or else you'll accidentally try to do things like delete comments, etc.
EDIT
Sorry, I didn't quite understand the question. I thought you were asking how to do an ajax request. Anyway, two things I'd try:
First, have your function echo just the word AJAX without the a tag. Next, try changing your ajax call so it has both a success and a complete callback:
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
var val = '';
jQuery(this).toggleClass('clicked');
jQuery.ajax({
type:'POST',
data:{action:'my_unique_action'},
url: "http://mysite/wp-admin/admin-ajax.php",
success: function(value) {
val = value;
},
complete: function(){
jQuery(this).html(val);
}
});
});
});
WordPress environment
First of all, in order to achieve this task, it's recommended to register then enqueue a jQuery script that will push the request to the server. These operations will be hooked in wp_enqueue_scripts action hook. In the same hook you should put wp_localize_script that it's used to include arbitrary Javascript. By this way there will be a JS object available in front end. This object carries on the correct url to be used by the jQuery handle.
Please take a look to:
wp_register_script(); function
wp_enqueue_scripts hook
wp_enqueue_script(); function
wp_localize_script(); function
File: functions.php 1/2
add_action( 'wp_enqueue_scripts', 'so_enqueue_scripts' );
function so_enqueue_scripts(){
wp_register_script( 'ajaxHandle', get_template_directory() . 'PATH TO YOUR JS FILE', array(), false, true );
wp_enqueue_script( 'ajaxHandle' );
wp_localize_script( 'ajaxHandle', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
File: jquery.ajax.js
This file makes the ajax call.
jQuery(document).ready( function($){
//Some event will trigger the ajax call, you can push whatever data to the server, simply passing it to the "data" object in ajax call
$.ajax({
url: ajax_object.ajaxurl, // this is the object instantiated in wp_localize_script function
type: 'POST',
data:{
action: 'myaction', // this is the function in your functions.php that will be triggered
name: 'John',
age: '38'
},
success: function( data ){
//Do something with the result from server
console.log( data );
}
});
});
File: functions.php 2/2
Finally on your functions.php file there should be the function triggered by your ajax call.
Remember the suffixes:
wp_ajax ( allow the function only for registered users or admin panel operations )
wp_ajax_nopriv ( allow the function for no privilege users )
These suffixes plus the action compose the name of your action:
wp_ajax_myaction or wp_ajax_nopriv_myaction
add_action( 'wp_ajax_myaction', 'so_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_myaction', 'so_wp_ajax_function' );
function so_wp_ajax_function(){
//DO whatever you want with data posted
//To send back a response you have to echo the result!
echo $_POST['name'];
echo $_POST['age'];
wp_die(); // ajax call must die to avoid trailing 0 in your response
}
Hope it helps!
Let me know if something is not clear.
Just to add an information.
If you want to receive an object from a php class method function :
js file
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
var data = {
'action': 'getAllOptionsByAjax',
'arg1': 'val1',
'arg2': $(this).val()
};
jQuery.post( ajaxurl, data, function(response) {
var jsonObj = JSON.parse( response );
});
});
php file
public static function getAllOptionsByAjax(){
global $wpdb;
// Start query string
$query_string = "SELECT * FROM wp_your_table WHERE col1='" . $_POST['arg1'] . "' AND col2 = '" . $_POST['arg2'] . "' ";
// Return results
$a_options = $wpdb->get_results( $query_string, ARRAY_A );
$f_options = array();
$f_options[null] = __( 'Please select an item', 'my_domain' );
foreach ($a_options as $option){
$f_options [$option['id']] = $option['name'];
}
$json = json_encode( $f_options );
echo $json;
wp_die();
}

Categories