2

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?

1
  • Don't use ajax in WordPress this way, Try this link instead Commented Jan 13, 2019 at 5:30

1 Answer 1

0

try including this in your authenticate-user.php file and place the file in the root directory.

require_once(dirname(__FILE__) . '/wp-config.php');

or give the relative path from the current directory

require_once(dirname(__FILE__) . '../wp-config.php');
Sign up to request clarification or add additional context in comments.

1 Comment

checked and updated the code... check this on your code

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.