简体   繁体   中英

How to receive a PHP response in Javascript

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM