-1

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);
        });
    });
});
  • Sorry but this is not a code review site, and in any case "efficient" greatly depends on your specific setup. – Mark Kaplun Sep 17 '18 at 4:40
  • My apologies Mark. I should have worded the question better. I was sort of asking how I could turn a function into a "real" function. I think janh has helped. – Corpuscular Sep 18 '18 at 1:31
0

I suppose the easiest way would be to have the action or other parameters in the button itself, i.e.

<div class="mybutton" data-action="get_quote" data-type="literary">Get a literary quote</div>
<div class="mybutton" data-action="get_quote" data-type="political">Get a political quote</div>

data-foo="bar" attributes can easily be accessed in jQuery with .data("foo"), so you could change the jQuery around a bit to listen to clicks on the class instead of a single ID:

jQuery(document).ready(function($) {
    $(".mybutton").click( function() {
        jQuery.post("/wp-admin/admin-ajax.php", { "action": $(this).data("action"), "type": $(this).data("type")}, function(response) {
            var obj = JSON.parse(response);
            $("textarea[name='myDiv']").val(obj.message);
            //console.log(response);
        });
    });
});

And voila, you'd now be able to pass data to the AJAX API by simply setting attributes in the button HTML. On the PHP-Side, you can check $_POST["type"] in your AJAX handler and react accordingly.

  • thanks for this suggestion @janh. I just wanted to let you know that I'll look at it and come back later. I am way out of my depth and need to read up on WP ajax before I can make this work I think. Cheers – Corpuscular Sep 18 '18 at 1:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.