Match javascript variable to php variable

Asked

Viewed 422 times

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?

  • 2

    You cannot do so inline, you need an ajax request to the server.

  • and without being by ajax, there is another alternative?

  • No. PHP runs BEFORE Javscript.

  • 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.

  • 1

    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.

  • And it is not possible to fetch the field name by php before the form is submitted?

  • Only by ajax. When the browser loads the page, PHP has already run.

  • @bfavaretto if pressing to an array, then how can I make the comparison? I’m thinking to go through this solution

  • If nomeDoArray.indexOf('valor') > -1 you mean you found

Show 4 more comments

1 answer

4


You’ll need to use Ajax to perform a query and return whether or not this car exists in the database. It is not possible to do it the way you want because the page has already been loaded.

Take a look at this link https://api.jquery.com/jQuery.ajax/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.