I am building a WordPress plugin to manipulate a custom table in the WordPress database from an Options Settings page. So far, I’m able to query the database and build an HTML table with the results.
ob_start();
// query the database and get the records
// $games contains the records
$htm .= '<table id="pl_table">';
// header
$htm .= '<tr>';
foreach ( $cols as $col ) {
$htm .= '<th>'.$col.'</th>';
}
$htm .= '</tr>';
// body
$htm .= '<tr>';
foreach ($games as $game){
foreach ($game as $val) {
$htm .= '<td>'.$val.'</td>';
}
$htm .= '</tr>';
}
$htm .= '</table>';
echo $htm;
$output = ob_get_contents();
ob_end_clean();
echo $output;
So far so good. Now I want to make the first column in the table a button that fires a javascript function.
$htm .= '<tr>';
foreach ($games as $game){
foreach ($game as $val) {
if ($game->ID == $val){
$htm .= '<td><button type="button" id="btn'.$val.'" onclick="myFunction()">'.$val.'</td>';
}
else {
$htm .= '<td>'.$val.'</td>';
}
}
$htm .= '</tr>';
}
Here is the function in my admin.js file:
function myFunction() {
document.getElementById("tboxOut").value = jsgame.ID;
}
In my main plugins page, I have enqueue’d the script file.
wp_enqueue_script('pl_script',plugins_url( 'js/admin.js', __FILE__ ));
When I open the page in a browser and click a button in column 1, the function fires and I can debug it in the browser.
Now, I need to pass the data in $game to this function and populate a bunch of input boxes, but have had no luck. Here is what I’ve tried:
$aryGame = (array)$game;
$htm .= wp_localize_script( 'pl_script', 'jsgame',$aryGame );
$htm .= '<td><button type="button" id="btn'.$val.'"onclick="myFunction()">'.$val.'</td>';
But in the browser debuger, I get an error: Uncaught ReferenceError: jsgame is not defined
Obviously, I’m missing some understanding on how to pass data from PHP to the javascript. Any ideas?
You need to use the correct hook (‘admin_enqueue_scripts’) on the server side, to load the js for the admin page and give it a handle. Then localize the js using the proper logic. And in the script, ensure that jQuery is in no-conflict mode (via jQuery(document).ready).
In other words, whatever is going on server side stays server side. There is nothing returned by the js function (myFunction), so it doesn’t make sense to say $.htm = wp_localize_script(). The object that is localized for js is either an array or a json encoded(str)/decoded(obj) type. If, after doing something with that data type within the script (client side), you want to post modified data back to the server, you do it by submitting the form to options.php. A submit button/event will trigger a php page refresh, so your server code can use the new data. But you’ll need to click the submit button, i.e., trigger the POST event.
Here’s how it should look:
In PHP
In JS
This solution is substantially based on this blog post by Pippins Plugins.