I have 20 buttons on a member protected wordpress page and each button gets a random record from a different custom table in the wp_ database.
@janh provided a solution here to get the random record using a php function and a js script.
However I wonder if there is a more efficient way to code up either the php function or the jquery so I don't have 20 copies of each?
In my freestanding prototype I used the onClick event and passed a variable which selected a different table in a php function getData(tableName) for each button. onClick="getData(1)" and onClick="GetData(2)"
However the current working solution does not use an onClick event in the jQuery and instead is called (I think) because the quote_refresh.js script has been "attached" to the element.
Options:
1: Create 20 different functions and 20 different js files and give each button a unique name.
2: Find some way to pass a button value to the wpse_314311_get_quote() function and use an if else statement to select the different table
3: Find some way to pass a value to the wp_enqueue_script script so it can pass a value to the quote_refresh.js script and attach to a different button
Please let me know if I can provide more info.
I'm very new to WP jquery and have no real idea of what functions might be available to solve this problem. I'm not even sure I'm explaining what I am after correctly.
the function in functions.php
function wpse_314311_get_quote() {
global $wpdb;
if($quote = $wpdb->get_row("SELECT fieldOne FROM myCustomTable ORDER BY RAND() LIMIT 0, 1")) {
print json_encode(array("success" => true, "message" => $quote->fieldOne));
}
else {
print json_encode(array("success" => false, "message" => "no quote found"));
}
// print json to client
exit;
}
add_action( 'wp_ajax_get_quote', 'wpse_314311_get_quote' );
wp_enqueue_script( "quote-refresh", get_template_directory_uri() . "/js/quote-refresh.js", array("jquery") );
and the quote_refresh.js
jQuery(document).ready(function($) {
$("#myButton2").click( function() {
jQuery.post("/wp-admin/admin-ajax.php", { "action": "get_quote"}, function(response) {
var obj = JSON.parse(response);
$("textarea[name='myDiv']").val(obj.message);
//console.log(response);
});
});
});