Support » Plugin: WP Data Access » Posting data to a High Score table

  • Resolved actionmanwaite

    (@actionmanwaite)


    Hi Peter – loving the WPDA Plug-in, which is very useful and beautifully constructed.

    I would like your help with a new application of the database for me. I would like to use a data table for the high score in a game. All visitors would see the same high score table and, obviously, I cannot allow the user to type in the score that they have achieved – I need to post the details into the table directly using code. I am coding in JavaScript.

    I appreciate that I will need to correspond with the database server using an AJAX call, but can you point me at an example which shows me how to address the correct datatable and POST in the data? (I think I can extract the results of the high score table using the usual short codes that you supply, although I will need to refresh the table once the new information has been provided to the database.)

    I understand that this is probably not best practice security wise – but I’m not too worried if super-smart programmers can get to the top of my leaderboard by cheating!

    Thanks in advance for your help. I have tried for two days to work this out but am new to using server-side databases and have got stuck.

    Thanks
    amw

    The page I need help with: [log in to see the link]

Viewing 13 replies - 1 through 13 (of 13 total)
  • Plugin Author Passionate Programmer Peter

    (@peterschulznl)

    Welcome actionmanwaite,

    Thanks for your compliments! 🙂

    You can use the Data Publisher to show your highscores. To update a table using ajax you need to setup a few things:
    (1) Your ajax call in the front-end
    (2) Your table update code in the back-end
    (3) The activation of your back-end code

    Implementing the ajax call wont be a problem I guess. You might want to check out how to use a wpnonce in your ajax call to prevent cheating.

    On the back-end you can update your database table from a php function. Here is a template for a possible implementation (already containing a wopnonce):

    public static function update_score() {
    	header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    	header("Cache-Control: post-check=0, pre-check=0", false);
    	header("Pragma: no-cache");
    	header('Content-Type: text/plain; charset=utf-8');
    
    	if ( !isset( $_REQUEST['score'] ) ) {
    		echo 'ERR-Wrong arguments';
    	}
    
    	// Get score (add values as needed)
    	$score = sanitize_text_field( wp_unslash( $_REQUEST['score'] ) );
    
    	// Check authorization
    	$wp_nonce = isset( $_REQUEST['wpnonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['wpnonce'] ) ) : ''; okay.
    	if ( ! wp_verify_nonce( $wp_nonce, "put-your-nonce-verification-text-here" ) ) {
    		echo 'ERR-Not authorized';
    		return;
    	}
    
    	// Perform your update here: replace ??? with your values
    	global $wpdb;
    	rows_update = $wpdb->update( ??? );
    
    	// Return update results
    	echo '' === $wpdb->last_error ? "UPD-{$rows_update}" : 'ERR-' . $wpdb->last_error;
    }

    Finally you need to activate the back-end code like this:
    add_action( ‘wp_ajax_mygame_update_score’, ‘update_score’ );
    And this if anonymous users are allowed to perform the call:
    add_action( ‘wp_ajax_nopriv_mygame_update_score’, ‘update_score’ );
    You can replace mygame_update_score with your own action and you must add this action to your ajax call.

    This is just a global setup. You need to fill in the details. Let me know if this helps you…

    Good luck! 🙂
    Peter

    Thread Starter actionmanwaite

    (@actionmanwaite)

    Thank you for the response Peter – makes sense. I will give it a go!

    Plugin Author Passionate Programmer Peter

    (@peterschulznl)

    Hi,

    Can you give me an update an the status of this topic? Can I close it?

    Thanks,
    Peter

    Thread Starter actionmanwaite

    (@actionmanwaite)

    Really helpful response Peter. Thank you very much. I ran into issues implementing it and (as someone self employed in Covid) work has taken unpredictable amounts of my time. Can I consult you next week if still struggling with implementation? After that, close as a job “well done”. Thank you for the support!

    Plugin Author Passionate Programmer Peter

    (@peterschulznl)

    No problem! 🙂 Let me know if I can help…

    Good luck,
    Peter

    Thread Starter actionmanwaite

    (@actionmanwaite)

    I still haven’t cracked it – but I’m confident the problem is with my coding not your plugin. Let me know if you offer coding lessons!

    Thread Starter actionmanwaite

    (@actionmanwaite)

    Sorry Peter, I still haven’t managed to pass a variable from JS into the DB. As you can see from the page (URL below) I have a “Test Function” button, and as a “test rig” all I want to do is pass the number “1” into the Database. Sounds easy, but I haven’t cracked it! Thanks for all your help so far.

    I’m using the following JS code in an HTML block on the web page (it’s generally functional, as I see “Test button clicked” but there is an error when I run the AJAX call which says “my_ajax_obj is not defined”). And I am running the PHP code (also copied below) using the “Code Snippets” plugin, although I am concerned about whether that code has the necessary admin rights when it runs. (I know that *I* have the admin rights, I’m not sure I have been able to grant them to the code!)
    I’m not concerned about security for this site (so have removed all the nonce code) and I want it to be accessible by an anonymous user. I’m also concerned that I haven’t had to use the database number / table … although I’m not even getting to those issues yet!
    I’m slightly concerned that I don’t have any wording that says “enqueue” – as that seems to be in many of the examples I have looked at in the documentation – and I’m also guessing that I have failed to “localize” variables (which I guess indicates I have a “training need”?).

    Is this a lost hope, or am I getting close?
    Thanks
    alex

    Web page HTML Block

    <script>
    jQuery(document).ready(function($) {             //wrapper
        $("button").click(function() {               //event triggers on clicking test button
            console.log("Test button clicked");
            var this2 = this;                        //use in callback
            $.post( my_ajax_obj.ajax_url, {          // THIS REFERENCE CAUSING ERROR***
                action: "mygame_update_card",        
                card: 1                              
            }, function(data) {                     //callback function (not needed YET!)
                console.log(data);                  // Will use $(this2)
            });                
        });
    });
    </script>
    
    <strong>Code Snippet</strong>
    
    <?php
    add_action( ‘wp_ajax_nopriv_mygame_update_card’, ‘updateDB’ );  // is_admin() is currently FALSE here, so do I need to change to run in Admin area???
    
    function updateDB() {
    	header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    	header("Cache-Control: post-check=0, pre-check=0", false);
    	header("Pragma: no-cache");
    	header('Content-Type: text/plain; charset=utf-8');
    	if ( !isset( $_REQUEST['card'] ) ) {
    		echo 'ERR-Wrong arguments';
    	} ;
    	// Get card (add values as needed)
    	$card = sanitize_text_field( wp_unslash( $_REQUEST['card'] ) );
    // Perform your update here: replace ??? with your values   HAVENT GOT THIS FAR YET
    //	global $wpdb;
    //	rows_update = $wpdb->update( ??? );
    // Return update results
    //	echo '' === $wpdb->last_error ? "UPD-{$rows_update}" : 'ERR-' . $wpdb->last_error;
    	echo 'well at least im here';
    }
    ?>

    /happy-50th-birthday-susan/

    Plugin Author Passionate Programmer Peter

    (@peterschulznl)

    Hi Alex,

    Is your request mygame_update_card served? Where did you put this code:

    add_action( 'wp_ajax_nopriv_mygame_update_card', 'updateDB' );

    If this code is in the wrong location, your server will not be able to handle the mygame_update_card request. You can test if the request is served with this URL:

    http://localhost/wp-admin/admin-ajax.php?action=mygame_update_card

    Please change the protocol and domainname according to your situation. What does this URL return?

    Thanks,
    Peter

    Thread Starter actionmanwaite

    (@actionmanwaite)

    I’m using Code Snippets plug-in for the PHP. (My original idea had been to edit Functions.PHP but the nice guys at WordPress Support told me that using Code Snippets does the same thing.)

    I tested the code with a simple “Echo” statement so I know that the snippets are running. HOWEVER, as you suggest I think one problem might be that the code is in the wrong place.

    I get “0” in response to your URL above (once I update the protocol and domainname). I take this to mean that it’s not being defined. Code Snippets has three different “scopes” for running the PHP but none of them seem to have Admin rights – which I assume I need? (I tested this with a simple if/Echo statements.)

    Where do I need to save the “add action” code? (I have full admin rights, I just dont know where to put the code so that the code had the admin rights!)

    Thanks for your continued, and super-responsive, support.
    alex

    Plugin Author Passionate Programmer Peter

    (@peterschulznl)

    Hi Alex,

    You cannot use the Code Snippets plugin to add hooks and filters. That code runs as a shortcode, that’s the wrong place… That is why you are getting a 0 as a response. Ones WordPress finds your function, you’ll get an error message, which is a good starting point.

    But, first things first… Your original idea to edit functions.PHP sounds like the right place to me. Although that file might be overwritten at some time. So, make sure you have a backup!

    Good luck,
    Peter

    Thread Starter actionmanwaite

    (@actionmanwaite)

    Thanks for your great help, Peter. I now have the hook working. (Proven by the fact that I can get more than a 0 from the test URL above … and also when I do my “if(!is_admin()) {}” test I get the right result!) I guess this means that Snippets isn’t the tool I needed – bit annoyed with the WordPress Support team about that.

    Anyway, progress – thank you – but I am not fully functional just yet. I may need more input in the days ahead. Very much appreciating your guidance.

    Thread Starter actionmanwaite

    (@actionmanwaite)

    Peter – Thanks again for your excellent support. I have got it working just the way I wanted it, essentially using the code that you posted and making sure that my PHP code was running in the back end.

    Apologies for the delay. I made the “School Boy Error” (although I’m sure School Girls are equally capable of the mistake) of temporarily pasting the code into an open window on my laptop – which happened to be MS Word – and when I pasted the code back into the code window the quotes had “become curly” and hence unrecognisable in PHP. This simple error cost me a day of de-bugging, and a week of elapsed time. A good lesson to learn. Is there a list of “really dumb mistakes”, or shall I start one?

    Appreciate your amazing dedication to supporting this Plugin. I’ve marked this one as resolved. (Of course … there is likely to be another query coming along shortly!)

    Plugin Author Passionate Programmer Peter

    (@peterschulznl)

    Great you got it working! 🙂 Good to hear I could help.

    I know about those mistakes. I made all of them… 🙂

    Best regards,
    Peter

Viewing 13 replies - 1 through 13 (of 13 total)
  • The topic ‘Posting data to a High Score table’ is closed to new replies.