how to validate form with ajax return

Asked

Viewed 965 times

1

I am unable to validate the form in this field that returns from ajax, function: validateVeiculos(); How to validate the checkbox that returns from ajax?

I have a main page.php where I declare the call by ajax, on this page I include "signup.php"; which returns in the main.php => Select the automaker...

call Ajax: Function buscarModelos(){ var assembler = $('#assembler'). val(); if(assembler){ // Alert('getVeiculos.php? assembler='+assembler); var url = 'getVeiculos.php? assembler='+assembler; $.get(url, Function(dataReturn) { $('#checkVeiculos'). html(dataReturn); }); }

Page code that returns ajax:

$montadora = ($_GET['montadora'] ? filter_var($_GET['montadora'], FILTER_VALIDATE_INT) : NULL); 
$idVeic = (!empty($_GET['idVeic']) ? filter_var($_GET['idVeic'], FILTER_VALIDATE_INT) : NULL);

$sql = "SELECT * FROM INTEGRAPRODUTOS.fipeVeiculos v WHERE v.IDmontadoraFipe = {$montadora} ORDER BY v.nomeVeiculo ";
$res = mysql_query($sql, $con_local);
$num = mysql_num_rows($res);
$html = '';

if(mysql_num_rows($res) > 0){



while ($dados = mysql_fetch_assoc($res)){
      //echo "<option value='{$dados_Subcategorias['codigo_subcategoria']}'>".utf8_encode($dados_Subcategorias[nome_subcategoria])."</option>";
      if($dados[idVeiculo] == $idVeic){
            ?>
        <div  class='box'; >&nbsp;<input type="checkbox" checked class="<? echo utf8_encode($dados['nomeVeiculo'])?>" id="veiculo" value="<? echo $dados['idVeiculo']?>" name="modelos[]" onClick="document.getElementById('listarFipe').click();" /><? echo utf8_encode($dados['nomeVeiculo'])."&nbsp;&nbsp;"?> </div>
          <?}   
          else {

            ?>
        <div  class='box'; >&nbsp;<input type="checkbox"  class="<? echo utf8_encode($dados['nomeVeiculo'])?>" id="veiculo" value="<? echo $dados['idVeiculo']?>" name="modelos[]" onClick="document.getElementById('listarFipe').click();" /><? echo utf8_encode($dados['nomeVeiculo'])."&nbsp;&nbsp;"?> </div>
          <?}  
     } 

}

Validation if you selected a checkbox of the page in ajax (this in the main.php):

<!-- validacao campos -->
<script type="text/javascript">
        //validar veiculos selecionados
        function validarVeiculos(){
        d = document.form;
        var ok = 0;
        var ckbox = d.getElementsByName('modelos[]');
            for (var i=0; i < ckbox.length; i++){
               if(ckbox[i].checked == true){
                ok = 1;
               }
           }

           if(ok == 0){
           alert('Selecione um veículo');
           return false;
           }
        }

function validaForm(){
           d = document.form;

    if (d.codMenil.value.length == 0) {
        alert("Digite um codigo");
        var codMenil = d.getElementByName(codMenil);
        d.codMenil.focus();
        return false;
    }

    if (d.Referencia.value.length == 0) {
        //alert("Digite uma Referencia");
        var Referencia = d.getElementByName(Referencia); //Seleciona o campo com a ID "nome"
        d.Referencia.focus();
        return false;
    }

    if (d.grupoCategoria.value.length == 0) {
        //alert("Selecione uma Categoria");
        var grupoCategoria = d.getElementByName(grupoCategoria);
        d.grupoCategoria.focus();
        return false;
    }

    if (d.Subcategorias.value.length == 0) {
        //alert("Selecione uma Subcategoria");
        var Subcategorias = d.getElementByName(Subcategorias);
        d.Subcategorias.focus();
        return false;
    }

    if (d.montadora.value.length == 0) {
        //alert("Selecione uma Montadora");
        var montadora = d.getElementByName(montadora);
        d.montadora.focus();
        return false;
    }

    validarVeiculos();


document.form.submit();
}  

I call the function that is inside

<input name="gravar" type="submit" value="Gravar" onclick="return validaForm()"/>

1 answer

1


One of the problems is that you are not manipulating the value returned by validarVeiculos(). Do the following:

if ( !validarVeiculos() ) {
    return false;
}
document.form.submit();

Note also that you never return true in this method, and the selector is wrong: use getElementsByName('modelos'), without the [].

Its function validarVeiculos() can be optimized: when a model is found checked, there is no need to iterate for the other models. And, if you want, you can make use of the method Array.some():

function validarVeiculos() {
    var i, ii, nodes;
    nodes = document.form.getElementsByName('modelos');
    for ( i = 0, ii = nodes.length; i < ii; i++ ) {
        if ( nodes[i].checked ) {
            return true;
        }
    });
    alert("Selecione um veículo!");
    return false;
}
  • I changed my function, but not valid: Function validaForm(){ d = Document.form; if (d.codMenil.value.length == 0) { Alert("Type a code"); var codMenil = d.getElementByName(codMenil); d.codMenil.Focus(); Return false; } if (d.Referencia.value.length == 0) { //Alert("Enter a Reference"); var Reference = d.getElementByName(Reference); //Selects the field with the ID "name" d.Referencia.Focus(); Return false; } validarVeiculos(); if ( !validarVeiculos() { Return false; } Document.form.Submit(); }

  • http://fiddle.jshell.net/9fsmhLdt/

  • I studied the routine better, I will not work with checkbox, I will use select, in this case I have implemented the validation in other selects with return ajax

  • @luisricardo do not put codes in comments... edit your question with the code, always identando, because it is much more readable. There’s a mistake in my code: getElementsByName does not return a Array and yes a NodeList, who does not have the method some. I will update my answer by reference only, since you modified the algorithm.

Browser other questions tagged

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