• I am working with wordpress. In wordpress I make a page ‘dm_page.php’ and in that use contact form 7 plugin in which I created the dropdownlist. On change event of dropdownlist I am hitting ajax. The code for ajax I wrote in header.php. The file to which ajax is giving the data is ‘getdata.php’ placed in theme folder. I am giving the code of ‘getdata.php’.

    <?php
    global $wpdb;
    
    $ddlval = $_POST['ddlval'];
    $results = $wpdb->get_row('select * from my_dynamictest where lang="'.$ddlval.'"', ARRAY_A);
    
    $someArray = [];
    array_push($someArray,[
        'id' => $results['id'],
        'name' => $results['name']
    ]);
    
    echo json_encode($someArray);
    
    ?>

    I am getting following error from this file in my ajax error callback:
    Fatal error: Call to a member function get_row() on null in…
    I am not able to figure this out what the error says. Please help. Consider me as total beginner in wordpress

Viewing 2 replies - 1 through 2 (of 2 total)
  • Dion

    (@diondesigns)

    The $wpdb variable is part of WordPress. Your AJAX handler isn’t loading WordPress, so the $wpdb variable isn’t available. Is this for a personal project, or are you writing something that will be distributed to others?

    If this is a personal project, you can avoid the H-U-G-E overhead of loading WordPress in your AJAX handler by using the built-in functions of the PHP mysqli extension to access your database.

    Otherwise you will need to include/require the wp-load.php file to load WordPress. That code would go at the top of your file, above the global declaration.

    And unless you want to open the door to SQL injection attacks, give some thought to using the mysqli_escape_string() function on the $_POST variable.

    Moderator bcworkz

    (@bcworkz)

    If this is not a personal project and you really do need to load WP, then you must not simply include/require wp-load.php because unless getdata.php is where it shouldn’t be, you cannot know for sure the relative or absolute location of wp-load.php on any given WP installation.

    All AJAX requests should be channeled through wp-admin/admin-ajax.php if you are keen to do things the proper WP way. See https://developer.wordpress.org/plugins/javascript/ajax/

    But Dion is basically correct, if you don’t really need to load WP, don’t do it!

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘fetching results through ajax in wordpress using wpdb class’ is closed to new replies.