0

I need to add some data to the user's meta on my website. To do so, I use ajax to call a PHP file on my server, however, when the code is executed, it just returns null instead of the user class. Here is the JS code:

<script>
    jQuery.ajax({
    type: "POST",
    url: 'https://mywebsite.com/wp-content/ajax/file.php',
    dataType: 'json',
    data: {},

    success: function (obj, textstatus) {
                      console.log(obj);
            }
});
</script>

And the contents of file.php are:

<?php
    header('Content-Type: application/json');
    global $current_user;
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    // 3 llines above are just to display the error if any
    get_currentuserinfo();
    echo json_encode($current_user->ID);
?>

When I execute this, the error says that Uncaught Error: Call to undefined function get_currentuserinfo() in...

When I delete this line, the output is just null. I don't know If I'm doing everything correctly, but feel free to suggest different solutions. I do not need the ID to be returned, but the $current_user variable should not be empty.

1 Answer 1

2

There isn't much of a reason to include a whole separate .php file to handle AJAX requests.

What's happening: Because you're including your own custom .php file, it's being included outside of the WordPress environment, so you don't have access to WordPress variables and functions.

You have two options:

  1. Use the built in AJAX methods, actions, and handlers

  2. "Include" WordPress in your custom .php file

I'd recommend the first method. It's (almost) as simple as using the wp_ajax_{$action} hook, and posting the request to admin-ajax.php instead of your custom file.

Your JS would look something like this:

jQuery.post(
    ajax_object.ajax_url,
    {action: 'my_action'},
    function( response ){
        alert( 'Here is the response: ' + response );
    }
);

And then inside your functions.php (or similar) file, enqueue and localize the JS:

// Wherever you are enqueing this JS file, use `wp_localize_script` to pass variables to it
wp_enqueue_script( 'your-script', $link_to_your_js, array('jquery') );
wp_localize_script( 'your-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

and then still in your functions.php or similar file, handle the request:

add_action( 'wp_ajax_my_action', 'my_action_function' );
my_action_function(){
    $user_info = get_currentuserinfo();
    wp_send_json( $user_info );
}

Alternatively, using the second method, you can include wp-load.php into your file.php, using one of the many answers on how to "include wp-load.php" in a file. This can cause some issues with scalability and maintenance though, so for something like this I'd strongly recommend the first method!

One last quick note: using wp_localize_script (like in the first method) you can actually pass the current user's information (or anything WordPress has access to, really) directly to the script, so you don't even need to make an AJAX request for it:

wp_localize_script( 'your-script', 'ajax_object', array(
    'ajax_url' => admin_url( 'admin-ajax.php' ),
    'current_userinfo' => get_currentuserinfo()
);

Doing that will allow the your-script JS file to have access to current_userinfo.ID and all the other variables available to it directly!

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

5 Comments

Could you, please, clarify what is supposed to be written instead of 'your-script' and $link_to_your_js. I am not too much of an expert in this topic, but I think I am supposed to write there a name of .js file, but what if it is embedded into HTML of the page?
If the script is just "embedded in the HTML" page, that's wrong as far as WordPress goes. Scripts should be properly enqueued. I would recommend you do that, if possible. If not, the quick and dirty solution is to use #2 and just include wp-load.php in your file.php file, just know that in doing do you're really branching away from using WordPress as it's intended and may make future diagnostics and scaling more painful
Thank you, that works like a charm! I was just confused that 'your script' can be an absolutely unassociated name. I ended up setting $link_to_your_js to content_url('ajax/get_meta.js').
Quick addition: what is the best way to pass an argument to php in this case? What I have done for now is just in js adding {action: 'my_action', arg: 'something'} and in php just writhing $arg = $_POST['arg']. Works fine, not sure if there will be any consequences tho :)
The your_script part is entirely arbitrary - just a descriptive handle so you can reference/remove/add to that script later programatically! Re: Args: it depends. If it's not sensitive data, passing it like that is perfectly fine (and, arguably, what you should be doing). If it is sensitive or needs authorization/user permissions, making an AJAX request to return the data is generally the best - as anything passed to the script through localization is able to be changed

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.