How to call a PHP function from Javascript in WordPress

I have a very simple plugin with a javascript file and a PHP file. I want to call the PHP file from my javascript code and get the output. The javascript functions is something like the following:

function img_upload(){

var ajax = new XMLHttpRequest();
ajax.open(‘GET’, ‘http://My_Domain_Name.com/wp-content/plugins/My_Plugin/auth.php’, false);
ajax.send();

if (ajax.status === 200) {

console.log(ajax.responseText);

}

and the PHP file which returns the results:

<?php
$token=Get_Token();
echo $token;
function Get_Token()
{
//Do some stuff
return $token;
}
?>

both files (auth.php and myjs.js) are in the root directory of the plugin.

/home/My_Username/public_html/wp-content/plugins/My_Plugin

If I use the domain name I can call the php file in ajax.open() and get the results, but I know this is not the right way to do that. How can I call the php file inside my javascrip code via ajax.open(‘path_to_php’) in WordPress properly without indicating the domain name?

Read more here:: How to call a PHP function from Javascript in WordPress

Leave a Reply

Your email address will not be published. Required fields are marked *