0

I've been stuck on this for the past day and it feels like I am missing something.

My assignment is:
Create a php file register.php which allows users to input their Name, Last name, Username and Email(via an HTML form) and then do some server-side verification on this data.
This file would also serve as an html form where users could input the data. For the Username input field I have to, on each keystroke, check if a user with that username already exists in my database.

This has to be accomplished using Javascript by sending a request to register.php with Ajax.

I know how to run the necessary query to search my database based on a certain username. That part is not a problem.

What I can't get to work is

  • using Javascript/Ajax to send a request to register.php
  • getting register.php to run a query based on the inputed username, since I don't know how to recieve the request
  • getting register.php to "return" a response without writing it out in the DOM

What I've tried so far:

let username= document.getElementById('username');
username.addEventListener('input', validateUsername);
function validateUsername(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            // Typical action to be performed when the document is ready:
            console.log(xhttp.responseText);
        }
    };
    xhttp.open("POST", "../obrasci/registracija.php", true);
    xhttp.send("username="+username.value);
}

this part works and I'm getting the whole HTML document back. I know that because the whole structure is being printed into the console.

now this is the part that I can't get to work. In PHP I've got this so far and I can't get the script to do anything with the username.

if( isset($_POST['username'])  ){
    json_encode($_POST['username']);
}

Edit: I forgot to add that this site needs to process the data sent with ajax dynamically(if that username is taken, mark the input as not okay until the user chooses a username that's not taken).
That might be a problem in the way I'm using this since the if in PHP only gets tested on first load?

Any help is appreciated.

6
  • The problem is that the if(isset($_POST['username'])) doesn't seem to trigger. So the error might be in the way I sent the data with xhttp.send Commented May 11, 2020 at 9:38
  • Go step by step with this, are you sure username is not set? Do something like echo isset($_POST['username']) ? 'username set' : 'no username'; die; and see what it returns. If there is indeed no username your request is doing something wrong. Maybe you are missing a correct header? try xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); Commented May 11, 2020 at 9:45
  • Are you trying to return the username as a json? if so return it using echo like so echo json_encode($_POST['username']); as it stands you are just encoding it but not giving the query any response Commented May 11, 2020 at 9:49
  • @MatthiasS this outputs no username, since when the site is first loaded the username is indeed not set. The username should be set only after the page loads and the user starts typing something into the username field(mind you, this is all supposed to happen dynamically, so there should be no submitting to check if the username exists, it should happen on keystroke). I'm not even sure if this works like that but that's what I'm trying to accomplish. Commented May 11, 2020 at 9:54
  • AH okay, so your register.php should be ajax endpoint AND form at the same time? Commented May 11, 2020 at 9:58

1 Answer 1

1

First, you can check whether or not the request was sent as a POST request (opening register.php in your browser will be a GET request).

You can wrap your form handling by something like this

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // check if username exists
  if (isset($_POST['username'])) {
    echo 'username: ' . $_POST['username'];
    die;
  } else {
    echo 'no username';
    die;
  }
}

change the code accordingly, use echo json_encode($data) to return your data in JSON format.

In your request, you might need to add the right header to tell PHP how to interpret the body sent with the request.

function validateUsername(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            // Typical action to be performed when the document is ready:
            console.log(xhttp.responseText);
        }
    };
    // add this line 
    xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhttp.open("POST", "../obrasci/registracija.php", true);
    xhttp.send("username="+username.value);
}

Also, make sure you have the right naming. In your code example, you refer to your input as the variable username, but you add the event listener to kor_ime, I don't know if you updated something to english and forgot other parts of it for this question or if that is your actual code

let username= document.getElementById('username');
username.addEventListener('input', validateUsername); // here change kor_ime to username and update the function name, you can omit the extra function wrapper
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I changed it to English for the purpose of this post but apparently forgot that part. It's correctly written in my code. Also, I just tried modifying my code like you said. Thank you so much. This fixed it!
Glad I could help. I know this is an assignment you are following, so probably not your choice, but in the long run, in my opinion, you should not have API-like responses (JSON) in the same file as HTML, as they fit different purposes and it makes it hard to maintain.
Yes, I completely agree with you. Making this has been a real struggle and I believe it would've been easier separating the checks into another php file. I actually lose points if I do that here though

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.