It is possible to do only with Javascript?
It is not possible to do this only with Javascript, as you require access to the database to verify that the record exists. That is, some language should be executed on the server side - nothing prevents it from being also Javascript, such as Nodejs, but it would be in a different context.
You can use PHP inside Javascript?
No. This is one of the most basic concepts of 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 depending on the protocol used, but the most common is HTTP. If you need to submit a Javascript value to PHP, you accurate send an HTTP request to the server. If you want PHP to return some value to Javascript, you accurate send them via the HTTP response that will be generated on the server.
I describe a little bit of this context here: How to write values to the Mysql database using PHP?
So how to proceed?
You should work on both fronts: Javascript and PHP. As Javascript, you should:
- Monitor the value of the email field in HTML by checking when there are changes in value;
- Check if the typed email is valid before making the request to the server;
- If you request without validating the email, you will be demanding unnecessary network resources;
- When e-mail is valid, make a GET request to the server;
- GET request is important for maintaining application semantics: you want to get a server state from base values;
- If the request is successful, check the body of the response;
- 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, since 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>
Considerations on the code:
- I did not implement the function of validating e-mail not to extend the code too much and for this to be easily found on the web;
- I also used the
email.validity
to compose the check;
- I used the event
input
, because this, theoretically, is triggered to any input event that can modify the value of the field, either via mouse, keyboard or touch; for more accurate application behavior, it is important that you manually set all desired events, since browsers still do not strictly follow the W3C or WHATWG specification in this issue;
- To request I used the API
fetch
; is experimental and the future replacement for XMLHttpRequest
, but works very well using the polyfill;
- I start the application with the disabled button and only enable it when the email is verified and available. This avoids that the user makes unnecessary requests to the server, with invalid or existing email, increasing the performance of the application and improving usability;
- If the request for verification fails, for any reason, I leave the button disabled to prevent the user to register, because I assume that, if there was an error with the verification, will occur, also, with the registration, then I warn the user of this embarrassing situation;
Already, on the server side, with PHP, you should:
- Check if the current request is a GET request;
- Check if the e-mail value has been correctly informed;
- Connecting to the database;
- Check the existence of the e-mail in the database table;
- Produce the response to be sent to the customer (browser);
- Effectively send the reply;
The code would be 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 the value 0 if the email is not registered or 1, otherwise with the status code of the response 200:
{exists: 0}
However, if any error occurs in the process, the response will have code 500 and a body stating the error message:
{error: 'O e-mail informado não é um e-mail válido'}
Study about AJAX.
– Woss
I think the most recommended would be an ajax request, within a Function Blur (Jquery) in the email field.. study these two techniques
– RickPariz
See my answer to the step-by-step how to do Ajax with Javascript only. Don’t forget to mark the answer if it helped you. Big hug!
– Sam