Is it possible to do only with JavaScript?
You can not do this with JavaScript, as you require access to the database to verify that the record exists. That is, some language should be run on the server side - nothing prevents JavaScript, such as NodeJS, but it would be in a different context.
Is it possible to use PHP within JavaScript?
No. This is one of the most basic concepts on the web and many people do not understand it correctly. PHP will run on the server side and JavaScript on the client side. The only way they both communicate is through messages. The format of the message may vary according to the protocol used, but the most common is HTTP. If you need to send a JavaScript value to PHP, you need to send an HTTP request to the server. If you want PHP to return some value for JavaScript, you need to send it through the HTTP response that will be generated on the server.
I describe a little of this context here: How to write values to the MySQL database using PHP?
p>
Then how to proceed?
You should work on both fronts: JavaScript and PHP. Like JavaScript, you should:
Monitor the value of the email field in HTML checking for changes in value;
Verify that the typed e-mail is valid before making the request to the server;
- If you make the request without validating the email, you will be demanding unnecessary network resources;
When the email is valid, make a GET request to the server;
- The GET request is important to maintain application semantics: you want to get a server state from base values;
If the request succeeds, check the response body;
If the request fails, you should inform that if the email already exists, the registration will fail - or not allow the person to register at this time, as the server may be in trouble;
So, in the code, we can have something similar to:
const email = document.getElementById("emailInput");
const button = document.getElementById("registerButton");
const messages = document.getElementById("messages");
function validate(email) {
// Implemente a função de validar e-mail aqui
return true;
}
email.addEventListener("input", function (event) {
if (this.validity.valid || validate(this.value)) {
fetch('verifica.php?email=${this.value}')
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error("Oops! Algo de errado não está certo...");
})
.then(json => {
if (json.exists) {
messages.innerHTML += 'E-mail já está cadastrado. Por favor, tente outro.';
} else {
messages.innerHTML += 'E-mail disponível.';
button.disabled = false;
}
})
.catch(error => {
messages.innerHTML += 'Falha no servidor, por favor, tente novamente mais tarde.';
});
}
});
<form action="cadastrar.php" method="POST">
<input id="emailInput" type="email" name="email" placeholder="Entre com o seu e-mail" required>
<button id="registerButton" type="submit" disabled>Cadastrar</button>
<div id="messages"></div>
</form>
Code Considerations:
I did not implement the function of validating email so as not to extend the code a lot and because it is easily found on the web;
I also used email.validity
to compose the verification;
I used the input
event because it is theoretically triggered for any input event that can modify the value of the field, either via mouse, keyboard or touch; for more accurate behavior of the application, it is important that you manually set all desired events, as browsers still do not follow the W3C or WHATWG specification in this regard;
To make the request, I used the fetch
API; is experimental and the future substitute for XMLHttpRequest
, but works fine using polyfill ;
Start the application with the button disabled and only enable it when the e-mail is verified and available. This prevents the user from making unnecessary server requests with invalid or existing e-mail, increasing application performance and improving usability;
If the verification request fails for any reason, I leave the button disabled to prevent the user from registering, as I assume that if an error occurred with the verification, it will also occur with the registration, then prevent the user from this embarrassing situation;
Now, on the server side, with PHP, you should:
Verify that the current request is a GET request;
Verify that the email value has been correctly entered;
Connecting to the database;
Check for email in the database table;
Produce the response to be sent to the client (browser);
Send the response effectively;
The code would look something like:
<?php
header('Content-Type: application/json');
try {
if ($_SERVER['REQUEST_METHOD'] != 'GET') {
throw new Exception("Não é uma requisição GET");
}
$email = filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL);
if (!$email) {
throw new Exception("O e-mail informado não é um e-mail válido");
}
$mysqli = require("db.php");
$stmt = $mysqli->prepare("SELECT EXISTS(SELECT 1 FROM emails WHERE email = ?) as 'exists'");
$stmt->bindParam(1, $email);
$stmt->execute();
$stmt->bind_result($row);
if ($stmt->fetch()) {
http_response_code(200);
$output = $row;
}
} catch (Exception $e) {
http_response_code(500);
$output = ['error' => $e->getMessage()];
} finally {
echo json_encode($output);
}
So, if all goes well, PHP will return a JSON response in the format below, with a value of 0 if the email is not registered or 1, otherwise with the status code of response 200:
{exists: 0}
However, if an error occurs in the process, the response will have code 500 and a body reporting the error message:
{error: 'O e-mail informado não é um e-mail válido'}