0

I am trying to check if a username is available in wordpress by using ajax with a php script backend, however am unsure of how to do this correctly.

In the checkusername.php script, I include WordPress's user.php like so:

require_once("../wp-includes/user.php");

I call username_exists( $_POST["username"] ) and am greeted with the following error:

Call to undefined function get_user_by() in ...\user.php on line 1613

Note I abbreviated the location. If I include pluggable.php I get a similar error but for

Class 'WP_User' not found in ...\pluggable.php on line 152

Honestly I don't really know how I am supposed to be correctly utilizing the user.php file outside of wordpress pagetemplates so if someone could help me that would be great.

4 Answers 4

2

If you are using ajax in WordPress, you don't need to do it "outside" of WordPress. WordPress has it's own filter hook system which allows for ajax callback functions to be run while having FULL access to all of WordPress's functionality.

Have a look at this: https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29

Here is a complete example of how to set up an ajax callback properly in WordPress:

PHP Code (place in plugin or functions.php file of theme)

//First enqueue your javascript in WordPress
function your_prefix_enqueue_scripts(){

    //Enqueue your Javascript (this assumes your javascript file is located in your plugin in an "includes/js" directory)
    wp_enqueue_script( 'your_unique_js_name', plugins_url('js/yourjavascriptfile.js', dirname(__FILE__) ), array( 'jquery' ) );

    //OR (simpler but not recommended)  
    wp_enqueue_script( 'your_unique_js_name', 'http://domain.com/myjavascriptfile.js', array( 'jquery' ) );

    //Here we create a javascript object variable called "youruniquejs_vars". We can access any variable in the array using youruniquejs_vars.name_of_sub_variable
    wp_localize_script( 'your_unique_js_name', 'youruniquejs_vars', 
        array(
            //To use this variable in javascript use "youruniquejs_vars.ajaxurl"
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
        ) 
    );  

}
add_action( 'wp_enqueue_scripts', 'your_prefix_enqueue_scripts' );

//This is your Ajax callback function
function your_ajax_callback_function_name(){

    //Get the post data 
    $username = $_POST["username"];

    //Run any WordPress function you want in this ajax callback
    if ( username_exists( $username ) ){
        $array_we_send_back = array( 'message' => __( 'This user exists', 'textdomain' ) );
    }
    else{
        $array_we_send_back = array( 'message' => __( 'This user does not exist', 'textdomain' ) );
    }

    //Make sure to json encode the output because that's what it is expecting
    echo json_encode( $array_we_send_back );

    //Make sure you die when finished doing ajax output.
    die(); 

}
add_action( 'wp_ajax_' . 'your_ajax_callback_function_name', 'your_ajax_callback_function_name' );
add_action( 'wp_ajax_nopriv_' . 'your_ajax_callback_function_name', 'your_ajax_callback_function_name' );

And then this goes in your javascript file:

jQuery(document).ready(function($){

    /**
     * When your ajax trigger is clicked
     *
     */
    $( document ).on( 'click', '.my-button', function(event){

        event.preventDefault();

        // Use ajax to do something...
        var postData = {
            action: 'your_ajax_callback_function_name',
            username: 'test_username_1',
        }

        //Ajax load more posts
        $.ajax({
            type: "POST",
            data: postData,
            dataType:"json",
            url: youruniquejs_vars.ajaxurl,
            //This fires when the ajax 'comes back' and it is valid json
            success: function (response) {

                alert( response.message );

            }
            //This fires when the ajax 'comes back' and it isn't valid json
        }).fail(function (data) {
            console.log(data);
        }); 

    });

});
Sign up to request clarification or add additional context in comments.

5 Comments

So now that I've created this javascript file, and put the two functions into functions.php, how do I actually get this functionality into my page template? And also, what is the "textdomain" in reference to? Thank you for your help.
Nevermind regarding the implementation of it. I had to add <?php wp_head(); ?> although I still don't know what "textdomain" is for.
You can find another answer about what a textdomain is in WordPress here wordpress.stackexchange.com/questions/75759/… Sidenote: if you have to call "wp_head()" you might be doing this in the wrong file. Make sure you aren't putting this code directly in a theme's file (unless it's the "functions.php" file). Putting it in a theme file directly is bad practice and should be avoided to prevent conflicts with other plugins or with missing action hooks.
I put the two functions in functions.php. I added wp_head() to the template, which I had removed it originally as I did not need any of its styling. Not sure what the better way to do that would be.
The only file wp_head() should be in is your "header.php" file in your theme. If that's what you are talking about than you're fine. You should take a look at the underscores theme to get a proper idea of how to create a theme: underscores.me
1

do not include files manually, use standard wordpress Ajax API

https://codex.wordpress.org/AJAX_in_Plugins

Comments

0

If you need access to WordPress function you will have to include wp-load.php

require_once("wp-contents/wp-load.php");

But this is not best practice, you shouldn't load the file directly.

Instead you can follow instructions on how to use WordPress ajax API as in the answer of kkarpieszuk (https://codex.wordpress.org/AJAX_in_Plugins)

Comments

0

These answers are fine if you are writing a plugin that is to be distributed out into the world, and you really need it to play nice with the rest of the WordPress landscape, and you don't care about performance. If you have a lot of plugins in your site... especially large ones like BuddyPress, then running ajax calls through the standard WP ajax pipeline can be very inefficient due to the fact that all of the plugins get loaded and processed, and the init routine gets called on all of the plugins for every ajax call. Coming from a non-WordPress world, this seems crazy to me. 99% of ajax calls don't need all of that infrastructure to be set up to do what they need to do.

To avoid this, set up your ajax php page to use the SHORTINIT code, and load the required files in the header. ( See also here: https://wordpress.stackexchange.com/questions/173002/how-declare-ajax-functions-ussing-shortinit )

For access to wpdb, get_current_user, and check_ajax_referer, I used the following the top of my ajax page:

N.B. our install has wordpress in the /wp folder, NOT the root folder! Your path names may be different

the file below might be something like /plugins/myplugin/my_ajax_event_handler.php ...and it would be called directly from $.ajax in the client javascript

<?php
define('SHORTINIT', true);

//IMPORTANT: Change with the correct path to wp-load.php in your installation
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp/wp-load.php';
include_once $path . '/wp/wp-includes/wp-db.php';
include_once $path . '/wp/wp-includes/formatting.php';
include_once $path . '/wp/wp-includes/capabilities.php';
include_once $path . '/wp/wp-includes/session.php';
include_once $path . '/wp/wp-includes/user.php';
include_once $path . '/wp/wp-includes/meta.php';
include_once $path . '/wp/wp-includes/pluggable.php';
wp_cookie_constants( );
wp_plugin_directory_constants();

my_ajax_event_handler();
function my_ajax_event_handler() {
    global $wpdb;

    // A nonce should be passed in from the client in the post field "security"
    check_ajax_referer( 'my_ajax_event_handler', 'security' );

    ... do all my cool ajax stuff ...

    die();
}
?>

Note that I'm working in a large corporate environment, and expect to be forced to do work to upgrade my code whenever we upgrade WordPress. This method works for me, but the normal wp_ajax_ way is definitely safer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.