Wordpress Ajax call not working on custom page - php

All seems in order, but still not getting destination populated.
So far I've verified that it can find the PHP and JS files within the plugin I created and even generate the output in XML. That I can see if I let the default <a> tag behavior.
Somehow it blocks where the output is generated.
Thanks
This is for a custom page.
1 - Here is the HTML:
Link to trigger ajax:
$link = admin_url('admin-ajax.php?action=pay_dialog_step1&boo_zone='.$palier['palier']);
'.get_option('_boopass_buybtn_label', '').'
Division to be populated:
<div id="alloconv_popup"></div>
2- PHP code in a plugin directory
add_action("wp_ajax_pay_dialog_step1", "pay_dialog_step1");
// ajax call
function pay_dialog_step1(){
$boo_zone = $_REQUEST['boo_zone'];
$response = new WP_Ajax_Response;
$html = '<div class="bp_entry_wrapper">
<div class="entry normal" >
<div class="alloconv_palier_header" >
<p> Alloconv ' . get_option('alloconv_' . $_REQUEST['boo_zone'] .'_token', '') . ' tokens </p>
</div>';
$html.= get_option('alloconv_' . $_REQUEST['boo_zone'] .'_script', '');
$html.= "</div>";
$html.= "</div>";
$response->add( array(
'data' => 'success',
'supplemental' => array(
'boo_zone' => $boo_zone,
'message' => $html,
),
) );
$response->send();
exit();
}
add_action('init', 'ajax_popup_script' );
function ajax_popup_script() {
wp_register_script( "ajax_popup_script", WP_PLUGIN_URL.'/ajax-popup-paiement/ajax_popup_paiement.js', array('jquery') );
wp_localize_script( 'ajax_popup_script', 'ajaxPaiement', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'ajax_popup_script' );
}
3- jquery code on same plugin directory
jQuery(document).ready( function() {
jQuery(".do_popup").click( function(e) {
e.preventDefault();
var link = this;
var boo_zone= jQuery(link).attr("id");
var info = {
action: 'pay_dialog_step1',
boo_zone: boo_zone
};
// Post to the server
jQuery.ajax({
type:"POST",
url:ajaxPaiement.ajaxurl,
data:info,
dataType:html,
success: function(data){
jQuery("#alloconv_popup").html(data);
}
});
});
});

You have to let wp know who can use the ajax calls.
wp_ajax is for the admin section
add_action('wp_ajax_process_ajax_input', 'callBackFunction_Name');
wp_ajax_nopriv is for non admin (users)
add_action('wp_ajax_nopriv_process_ajax_input', 'callBackFunction_Name');
This is the call back function that will then process your ajax call.
function callBackFunction_Name{
$allFields = $_REQUEST;
#todo process input.
}

I finally found what the issue was. Simply, on the ajax call, the data type should be 'xml' instead of 'html.
The WP_Ajax_Response generates an XML file, so one needs to adapt the ajax call accordingly.

Related

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!");
});

Passing variable from Ajax to PHP in WordPress plugin

I am developing a WordPress plugin and I am trying to pass a variable from ajax to a php file. Both files are inside my plugin folder. The js file is running but when I fire the ajax function, it seems that is not sending a post.
Plugin structure:
-plugin folder
--ajax.js
--folder/example.php
This is my ajax.js
// using jQuery ajax
// send the text with PHP
$.ajax({
type: "POST",
url: "/absoluteurlpluginfolder/folder/example.php",
data: {
'action': 'my_action',
'whatever': 1234
},
// dataType: "text",
success: function(data){
console.log('Connection success.');
// console.log(data);
}
});
And this is my example.php
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
alert($whatever);
wp_die(); // this is required to terminate immediately and return a proper response
}
I have two problems:
I cannot see that example.php is receiving anything
How could I use a relative URL to connect with my PHP file? When I try such as 'url: "folder/example.php",' it seems that it starts with "http://localhost/my-wp-project/wp-admin/" and not in my plugin folder, and fails.
I think that the main problem was that I need to add "wp_enqueue_script" and "wp_localize_script". However, I am working in the development of a TinyMCE plugin inside WordPress.
That means that although the JS file is already include, it is not working when I add "wp_enqueue_script" and "wp_localize_script". Why? I do not know but the strange thing is that I made it working with another line.
wp_register_script( 'linked-plugin-script', null);
I have tried with different versions, and the minimum necessary to work is this one above. I can put the URL, version, jquery dependency and false or true. All of them work.
So at the end this is my code and is working.
This is the plugin.php
// Include the JS for TinyMCE
function linked_tinymce_plugin( $plugin_array ) {
$plugin_array['linked'] = plugins_url( '/public/js/tinymce/plugins/linked/plugin.js',__FILE__ );
return $plugin_array;
}
// Add the button key for address via JS
function linked_tinymce_button( $buttons ) {
array_push( $buttons, 'linked_button_key' );
return $buttons;
}
// Enqueue the plugin to manage data via AJAX
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
wp_register_script( 'linked-plugin-script', null);
wp_enqueue_script( 'linked-plugin-script');
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'linked-plugin-script', 'ajax_object', array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'whatever' => '' )
);
}
// Same handler function...
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$whatever = strtoupper($_POST['whatever']);
echo $whatever;
wp_die();
}
And this is the plugin of TinyMCE in JavaScript
// JavaScript file for TinyMCE Linked Plugin
//
//
//
( function() {
tinymce.PluginManager.add( 'linked', function( editor, url ) {
// Add a button that opens a window
editor.addButton( 'linked_button_key', {
// Button name and icon
text: 'Semantic Notation',
icon: false,
// Button fnctionality
onclick: function() {
// get raw text to variable content
var content = tinymce.activeEditor.getContent({format: 'text'});
// using jQuery ajax
// send the text to textrazor API with PHP
$.ajax({
type: 'POST',
url: ajax_object.ajax_url,
data: { 'action': 'my_action',
'whatever': ajax_object.whatever = content
},
beforeSend: function() {
console.log('before send..');
},
success: function(response){
console.log('Success the result is '+response);
}
});
} // onclick function
} ); // TinyMCE button
} ); // tinymce.PluginManager
} )(); // function
Have you seen this page? This is the best tutorial. But you have missed a few things:
You should set global js variable with wp_localize_script() function. Like
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
Replace your url in JS to ajax_object.ajax_url.
IF you wanna work ajax with wp_ajax hooks - you should send all your requests do wp-admin/admin-ajax.php. You can get this url by admin_url('admin-ajax.php');.

Wordpress: Why am I getting a 400 from ajaxurl?

I'm trying to implement basic ajax. I've been following this tutorial. My JS fires when I click the button but I get a 400 from the ajax url: POST http://localhost:8080/wp-admin/admin-ajax.php 400 (Bad Request)
As far as I can tell, I haven't strayed far from the tutorial code. Her is my JS:
jQuery(document).ready(function($){
$('#baa_form').submit(function(){
var data = {
action: 'baa_response'
}
$.post(ajaxurl, data, function(response){
alert('Hello');
});
return false;
});
});
PHP:
<?php
function baa_add_menu() {
global $baa_settings_page;
$baa_settings_page = add_menu_page( 'Basic Admin Ajax', 'Basic Admin Ajax', 'edit_pages', 'basic-admin-ajax', 'baa_render_settings_page', false, 62.1 );
}
function baa_load_scripts( $hook ) {
global $baa_settings_page;
if ( $hook !== $baa_settings_page ) {
return;
}
$path = plugin_dir_url( __FILE__ ) . 'js/basic-admin-ajax.js';
wp_enqueue_script( 'basic-admin-ajax', $path, array( 'jquery' ) );
}
add_action( 'admin_menu', 'baa_add_menu' );
add_action( 'admin_enqueue_scripts', 'baa_load_scripts' );
function baa_render_settings_page() {
?>
<form id="baa_form" method="POST">
<div>
<input type="submit" name="baa_submit_button" id="baa_submit_button" class="button-primary" value="go ajax">
</div>
</form>
<?php
}
function baa_response() {
die( 'I got died' );
}
I've had a look inside admin-ajax.php and the only reason for returning a 400 that I can see is if I've failed to set an action. data['action'] is certainly set, unless I'm crazy.
Am I doing anything that's obviously wrong? What could be causing the 400 response?
update
To clarify, the JS fires but the request to admin-ajax.php receives a 400. You can see where the tutorial make has implemented similar JS here. (I haven't added a nonce yet but the video maker had already demonstrated it working without implementing a nonce.)
edit
I've updated the PHP to show the plugin's entire PHP file.
update 2
I've stripped the JS back to the essentials and followed the top example from Wordpress. The response is still 400. Which leads me to believe that it might be something I've overlooked in the php. At the moment, I don't understand why or what it might be.
jQuery(document).ready(function($) {
var data = {
'action': 'baa_response'
};
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
You missed action, which will fired on your Ajax request. WordPress can't guess which function related to your Ajax call, and that's why just blocking it( 400 Bad Request ).
In the php file add this line:
add_action('wp_ajax_baa_response', 'baa_response');
You may also want to look at the Ajax in Wordpress documentation.
Please try like this,
Add this to your functions.php,
$path = plugin_dir_url( __FILE__ ) . 'js/basic-admin-ajax.js';
wp_enqueue_script( 'basic-admin-ajax', $path, array('jquery'), '1.0', true );
wp_localize_script( 'basic-admin-ajax', 'action_linklist', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
));
function baa_response() {
echo "something.....";
die();
}
in your JS file,
jQuery(document).ready(function($){
$('#baa_form').submit(function(){
jQuery.ajax({
url: action_linklist.ajax_url,
type: 'post',
data:{'action': 'baa_response'},
success: function (response) {
alert(response);
}
});
return false;
});
});
Hope this will helps you,
For more information, please visit.
Using AJAX with wordpress
AJAX in Plugins

How to receive data from database via jquery? [wordpress .js]

I am trying to fetch few data from database in my .js file of wordpress theme.
I tried with .post() of jquery but nothing is happening.
Please also suggest me any alternate.
code in .js file
jq.post("../abc.php",
{
name:"kumar",
accId:window.accommodationId
}, function(data,status)
{
alert("hello");
//alert("Data: " + data + "\nStatus: " + status);
}
);
code in abc.php file
<?php
global $wpdb;
$max_minAge = $wpdb->get_results( "SELECT price_per_day FROM wp_byt_accommodation_vacancies where accommodation_id='1741'" );
echo $max_minAge[0]->price_per_day;
?>
you can use wp_ajax hooks like this in your functions.php file
// script atyle add at frontend
add_action( 'wp_enqueue_scripts','my_scripts_style');
function my_scripts_style()
{
wp_enqueue_script( 'scriptid', PATH_TO . 'script.js', array('jquery') );
// localize the script
wp_localize_script( 'scriptid', 'myAjax', array( 'url' =>admin_url( 'admin-ajax.php' ),'nonce' => wp_create_nonce( "ajax_call_nonce" )));
}
Then add the ajax hook
// action for execute ajax from frontend
add_action( 'wp_ajax_nopriv_execute_ajax','execute_ajax');
function execute_ajax()
{
$nonce = check_ajax_referer( 'ajax_call_nonce', 'nonce' );
if($nonce==true)
{
// here you will perform all the db communication get data from db and send it to the view area.
echo 'test this';
die();
}
}
then in your js file which you included via enque_script above. use this
jQuery(function(){
jQuery('.click-onthis').live('click', function(){ // get data by click
var data = {
action: 'execute_ajax',
nonce: myAjax.nonce,
// anyother code etc
};
jQuery.post( myAjax.url, data, function(response)
{
if(response=='success')
{
}
});
});
});
jquery click-on-this will work when click on a link you can coomunicate on load or any other event
You can use the jQuery AJAX get shorthand:
$.get( "../abc.php", function( data ) {
alert( "Data Loaded: " + data );
});
Good to know: Since you're getting data from a file, you should use a GET.

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