TL;DR: Not Dupe - Code first, scroll to bottom for problem.
Here is the link to the demo that I currently have.
In functions.php
I localize my script first:
function ajaxurl(){
wp_enqueue_script( 'product-selector', get_template_directory_uri() . '/js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'product-selector', 'MyAjax', array(
// URL to wp-admin/admin-ajax.php to process the request
'ajaxurl' => admin_url( 'admin-ajax.php' ),
// generate a nonce with a unique ID "myajax-post-comment-nonce"
// so that you can check it later when an AJAX request is sent
//'postCommentNonce' => wp_create_nonce( 'myajax-post-comment-nonce' ),
)
);
}
add_action('wp_head', 'ajaxurl');
And then for the script my ajax calls on I have:
function ajax_callback() {
global $wpdb; // this is how you get access to the database
// Declare our variable.
$cat = $_POST['cat'];
// Q the DB
$query = $wpdb->get_col( $wpdb->prepare(
"
SELECT meta_value
FROM $wpdb->postmeta
WHERE post_category=%s
", $cat
) );
header('Content-Type: application/json');
wp_send_json( json_encode( $query ) );
}
add_action( 'wp_ajax_nopriv_ajax-callback', 'ajax_callback' );
And finally for ajax.js I have:
$(document).ready(function(){
var back_end_script_url = MyAjax.ajaxurl;
$(function() {
var category_callback = function(data) {
console.log(data);
var adhesion_select = $('#adhesion');
var substrate_select = $('#substrate');
substrate_select.find('option').remove();
adhesion_select.find('option').remove();
for (var k in data) {
var option = $('<option />').val(k).html(data[k]);
adhesion_select.append(option);
}
};
var adhesion_callback = function(data) {
console.log(data);
var substrate_select = $('#substrate');
substrate_select.find('option').remove();
for (var k in data) {
var option = $('<option />').val(k).html(data[k]);
substrate_select.append(option);
}
};
var category_change = function() {
console.log('Category Changed');
var category = $(this).find(":selected").val();
var params = {
action: 'ajax-callback',
cat: category
};
console.log(params);
$.post(back_end_script_url, params, category_callback);
};
var adhesion_change = function() {
console.log('Adhesion Changed');
var adhesion = $(this).find(":selected").val();
var category = $('#cat').find(":selected").val();
var params = {
action: 'ajax-callback',
cat: category,
adhesion: adhesion
};
console.log(params);
$.post(back_end_script_url, params, adhesion_callback);
};
$('#cat').on('change', category_change);
$('#adhesion').on('change', adhesion_change);
});
});
So my problem is, if you look at the demo, the ajax only returns the number 0, not the data from the db.
I have read every related question on this problem on stack and wordpress exchanges, and tried all of them out, and my result is always the same.
I hired out the JS code, but the guy swears its on my end. I'm not sure if that's true or not, because I can't find any problem in my code.
Thanks for your help, Stack!