PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, March 2, 2022

[FIXED] Adding user meta from Javascript

 March 02, 2022     ajax, javascript, php, wordpress     No comments   

Issue

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.


Solution

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!



Answered By - Xhynk
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing