I am new to PHP and WordPress development.
On my WordPress page I want to check whether the aff_id
in my page's query string is present as a user in my WordPress DB using AJAX.
Below is the JavaScript which I have placed on my WP page using "Scripts and styles" plugin:
var affId = '';
affId = GetParameterValues('aff_id');
if (affId == undefined || affId == '')
affId = 'AKotawala';
const xhr = new XMLHttpRequest();
xhr.onload = function () {
alert(this.responseText);
};
xhr.open("POST", "../wp-includes/authenticate-user.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("username=" + affId);
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
And here's my PHP code
authenticate-user.php
<?php
$username = $_POST['username'];
if (my_username_exists($username))
echo "Exist";
else
echo "NotExist";
function my_username_exists($username) {
global $wpdb;
$count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(user_login) FROM $wpdb->users WHERE user_login = %s", $username));
return empty( $count ) || 1 > $count ? false : true;
}
?>
When the page loads my alert box is empty.
What am I doing wrong?
When I hard code the $username
variable in my PHP and run the file as mydomain.com/wp-includes/authenticate-user.php
it returns a blank page.
Am I placing authenticate-user.php
in the right folder?
If yes what should be the url I should pass to my AJAX function in JS?