2
I have a form, and before the form is submitted I want to validate if the field nome_carro
exists the same in the database. To do this validation I am using javascript.
On the form I have the following:
<form method="post" action="" name="add_form" onsubmit="return validateForm()">
<input type="text" name="nome_carro" required="">
.
.
.
</form>
And in javascript the following:
<script>
function validateForm()
{
var x=document.forms["add_form"]["nome_carro"].value;
<?php
$nome_carro = "VARIAVEL X, NO JAVASCRITP";
//fazer query, mas para isso preciso da variavel $nome_carro preenchida
?>
var nome_carro_bd = <?php $valor_retornado_da_consulta?>;
if(x == nome_carro_bd)
{
alert("Por favor, insira outro nome na viatura. O nome que colocou já existe.");
return false;
}
}
</script>
To validate javascript, I have to query the BD (using php) to see if the name already exists. For this I need to match the variable x
a php variable to query. How can I do this?
You cannot do so inline, you need an ajax request to the server.
– bfavaretto
and without being by ajax, there is another alternative?
– pc_oc
No. PHP runs BEFORE Javscript.
– Henrique Barcelos
I believe that the most practical way to perform this procedure would be to use an ajax, in case there is no problem I can help with the script.
– Alessandro Gomes
Only if you store all the database values in a js array before generating the page, and then see if the field value is in the array. If there are many, it is not recommended.
– bfavaretto
And it is not possible to fetch the field name by php before the form is submitted?
– pc_oc
Only by ajax. When the browser loads the page, PHP has already run.
– bfavaretto
@bfavaretto if pressing to an array, then how can I make the comparison? I’m thinking to go through this solution
– pc_oc
If
nomeDoArray.indexOf('valor') > -1
you mean you found– bfavaretto