• Will S

    (@stedmanw)


    Hello,

    I was able to get the issue (POST request) from my previous forum question working with much appreciated help from Gerry @metamezzo in order to get data from wordpress page posted into a database table. Thank you so much Gerry for your help!! Now, I’m trying to get the GET request working in order to get data from database table into my wordpress page.

    If someone can take a look and see where I’m going wrong, it would be very appreciated! As I mentioned in previous post, I’ve spent so much time trying to figure this out myself but almost everything that I find is just posting using a form. There seems to be very little on how to use WordPress hooks beyond the documentation, which I’ve tried in vain to figure out.

    Below is the relevant code for what I’m trying to do: get the value ‘1000’ from ‘adapt’ column of database table (MLT_Exam_db) and retrieve it and display it on wordpress page <div> where id = #retrieveAdapt.

    1. Portion of?html widget?inserted into Elementor page on WP site with field in which to display data from db.
    2. functions.php?code using hooks to GET data from db
    3. javascript script?to create object to GET data from db

    Thanks!

    Will S.

    // ——— HTML Widget ——— 
    
    //left out top part of html document
    
    <body>
        <button id="getFromDbButton" onclick="getFromDbButtonFxn()" >Get from Database</button>
        
    <div>Value retrieved from db: <span id="retrieveAdapt"></span></div>
    
    
       
    </body>
    
    // ——— functions.php ——— 
    
    //left out the code for child hello theme
    
    function register_flashcard_scripts2() {
    	wp_register_script('flashcard_settings2', get_stylesheet_directory_uri() . '/scripts/getFromDB.js', array('jquery'));
    	wp_localize_script('flashcard_settings2', 'FlashcardApp2', array(
    		'ajaxurl' => admin_url('admin-ajax.php'),
    		'user_id' => get_current_user_id()
    	));
    	
    	wp_enqueue_script('flashcard_settings2');
    }
    
    
    add_action('wp_enqueue_scripts', 'register_flashcard_scripts2');
    
    
    
    
    function save_flashcard_settings2() {
    	global $wpdb;
    	$adaptValueFromDb = intval($_GET['adapt']);  // TRYING TO GET 'adapt' VALUE FROM DB	
    	$query = "SELECT adapt FROM MLT_Exam_db WHERE adapt=' .$adaptValueFromDb. '";
    	$result = $wpdb->query($query);
    }
    
    
    
    
    add_action('wp_ajax_save_flashcard_settings2', 'save_flashcard_settings2');
    add_action('wp_ajax_nopriv_save_flashcard_settings2', 'save_flashcard_settings2');
    // ——— getFromDB.js ——— 
    
    jQuery(document).ready(function ($) {
    	var $flashcard_exit_btn2 = $('#getFromDbButtonFxn');
    
    	if ($flashcard_exit_btn2.length !== 0) {
    		$flashcard_exit_btn2.on('click', function (e) {
    			if(confirm('Warning:')) {
    				$.ajax({
    
    					type: 'GET',
    					dataType: 'json',
    					url: FlashcardApp2.ajaxurl,
    					aync: false,
    					data: {
    					action: 'save_flashcard_settings2',  // RUN PHP SCRIPT:  
    
    					adaptValueFromDb: document.querySelector('#retrieveAdapt').innerHTML,
    					adaptValueFromDb: $adaptValueFromDb
    					},
    				
    					error: function(xhr, textStatus, error) {
    						window.location.reload();
    					},
    					success: function(data) {
    						window.location.reload();
    					}
    				});
    			
    				e.preventDefault();	
    			} else {
    				window.location.reload();
    			}
    		});
    	}
    });
    
Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    Your save_flashcard_settings2() function (Ajax handler) should echo out the data you want returned to your jQuery caller. If it’s a singleton value you could echo it out directly, but if the data is structured you may need to JSON encode it.

    After sending out the data your Ajax handler needs to exit(); or die();

    In your jQuery you wouldn’t want to reload the page on successful Ajax call. Instead insert the returned data into the appropriate spot in the DOM.

    FWIW, using “save” in function and action hook names is probably not the best choice when you’re getting, not saving. While it will work, it’s confusing and could hamper future code maintenance. I realize you’re just recycling code from earlier, but consider what effect misleading names will have when you need to modify this code after not seeing it for many months ??

    Thread Starter Will S

    (@stedmanw)

    Hi (@bcworkz),

    Thanks for your input! I tried following your suggestions:

    1. I have 2 methods for trying to echo out value from db. In the 2nd method i tried echoing a <h1> with id tag that i reference in the js file.
    2. I changed the js file so that upon “success” the code should get the php value echoed out and then set equal to div on html page.

    Please let me know if i’m getting close and what changes to make. I have to admit the syntax is a little challenging. I coded my whole site in vanilla js and so am used to that.

    Thanks!

    Will

    function save_flashcard_settings2() {
    	global $wpdb;
    
    	//$adaptValueFromDb = intval($_GET['adapt']); 
    
    	$query = "SELECT * FROM MLT_Exam_db";
     
    	$result = $wpdb->query($query);
    
            // METHOD 1
            echo $adaptValueFromDb;
    
            // METHOD 2
            echo "<h1 id='phpValue'>$adaptValueFromDb </h1>"; 
    }
    
    
    
    add_action('wp_ajax_save_flashcard_settings2', 'save_flashcard_settings2');
    add_action('wp_ajax_nopriv_save_flashcard_settings2', 'save_flashcard_settings2');

    // ——— getFromDB.js ——— 
    
    jQuery(document).ready(function ($) {
    	var $flashcard_exit_btn2 = $('#getFromDbButtonFxn');
    
    	if ($flashcard_exit_btn2.length !== 0) {
    		$flashcard_exit_btn2.on('click', function (e) {
    			if(confirm('Warning:')) {
    				$.ajax({
    
    					type: 'GET',
    					dataType: 'json',
    					url: FlashcardApp2.ajaxurl,
    					aync: false,
    					data: {
    					action: 'save_flashcard_settings2',  // RUN PHP SCRIPT:  
    
    					
    					
    					},
    				
    					error: function(xhr, textStatus, error) {
    						window.location.reload();
    					},
    					success: function(data) {
    		
    getPhpValue: document.querySelector('#phpValue').innerHTML;	
    
    getDivValue: document.querySelector('#retrieveAdapt').innerHTML;			
    
    getDivValue: getPhpValue;
    				
    					}
    				});
    			
    				e.preventDefault();	
    			} else {
    
    window.location.reload();
    
    			}
    		});
    	}
    });
    Moderator bcworkz

    (@bcworkz)

    After sending out the data your Ajax handler needs to exit(); or die(); I think failing to do so might inhibit output from actually being sent out. IIRC echoed data just sits in a buffer until execution ends.

    As printed here, $adaptValueFromDb is undefined. (assignment commented out) I think you meant to use $result in its place. Even if undefined, the other static HTML should still be output once execution is terminated.

    $result will be an array, not a singleton value. You cannot directly echo out an array in a way that will be meaningful to jQuery. Either JSON encode it or parse it with PHP to build the desired HTML content string prior to output.

    I know it’s now commented out, but you use a value from $_GET. There is no evidence you’ve sent such a value from your jQuery. Perhaps you’ve deleted that element instead of commenting it out?

    I’ll assume FlashcardApp2.ajaxurl has a correct URL value. Be sure any URLs used within WP are full, absolute URLs. You want to avoid using relative file references in WP.

    I’m not that good with jQuery, but your success: procedure isn’t doing anything with the data returned from the server that’s in data. For now you could just console log it so you can see what was returned.

    As an initial effort, making an Ajax request with a singleton value that is simply returned by the server is a good choice. Once you are able to get data to make a successful round trip you’ve won half the battle. Don’t try to do anything fancy like a DB query for now. You first want to get the basic mechanics of Ajax working. Once you get that you can build upon your success with something more meaningful.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘WP Hook + JQuery GET from WP DB’ is closed to new replies.