Problem with AJAX result in a required jQuery rule Validate

1

I have an incident with an answer that I have in an AJAX, all this within a depends of a rule required in a JS with jQuery Validate for the validation of a form.

I leave the code that I am running:

$('#form').validate({
  ignore: '[readonly=readonly]',
  errorPlacement: function (error, element) {
    var lastError = $(element).data('lastError'), newError = $(error).text();
    $(element).data('lastError', newError);
    if (newError !== '' && newError !== lastError) {
      $(element).popover({
        trigger: "manual",
        placement: "auto top",
        content: newError,
        container: "body",
        template: "<div class=\"popover\" role=\"tooltip\"><div class=\"arrow\"></div><div class=\"popover-content\"><p></p></div></div>"
      });
      if (element.is(':hidden')) {
        $(element).next('span').popover('show').addClass('has-error').removeClass('has-success');
        console.log('hidden element');
      }else {
        $(element).popover("show").parents(".form-group").addClass('has-error').removeClass('has-success');
        console.log('normal element');
      }
    }
  },    
  success: function (label, element) {
    $(element).popover("hide").parents(".form-group").removeClass('has-error').addClass('has-success');
  },
  rules: {
    "3_nombre[]": {
      maxlength: 500,
      required: {
        depends: function(element){
          var id=$(this).parents('table').attr('id');
          var rut_p=$('#'+id+' #3_rut').val();
          var xurl="vws/ajax_validar_rut.php?rut="+rut_p;
          $.ajax({
            url: xurl,
            type: "GET",
            success: function(data){
              // alert(1);
              if( data==0 ){
                // alert(2);
                if($('.3_rut').val() !='' || $('.3_ape_p').val() !='' || $('.3_ape_m').val() !='' ){
                  // alert(3);
                  return true;
                }else {
                  // alert(4);
                  return false;
                }
                // return true;
              }else {
                // alert(5);
                return false;
              }
            }
          });
        }
      }
    },
  }
});

Then it is understood that this required , must receive a 'TRUE' or a 'FALSE'. But he does not receive it. I'm missing something, is there an error that the debugger is not seeing?

I still needed to describe that the 'xurl' - > 'ajax_vallidar_rut.php' validates the rut itself (which is legitimate) and whether or not it is greater than a range to identify whether it is a company or a natural person. This returns a '0' or a '1' which is what is then valid in the success of the AJAX.

UPDATE

I had found a solution, but it is outdated. It was just the issue of async=false in the AJAX, keeping me that way;

"3_ape_p[]": {
maxlength: 500,
required: {
    depends: function(element){
        var id=$(this).parents('table').attr('id');
        var rut_p=$('#'+id+' #3_rut').val();
        var xurl="vws/ajax_validar_rut.php?rut="+rut_p;
        var bRequired=false;
        $.ajax({
            async: false,
            url: xurl,
            type: "GET",
            success: function(data){
                if( data==1 || data==0 ){
                    if($('.3_rut').val() !='' || $('.3_ape_m').val() !='' || $('.3_direccion').val() !='' || $('.3_num').val() !='' || $('.3_comuna').val() !='' || $('.3_email').val() !='' || $('.3_tel').val() !='' || $('.3_fax').val() !=''){
                        // return true;
                        bRequired=true;
                    }else {
                        // return false;
                        bRequired=false;
                    }
                    // return true;
                }else {
                    // return false;
                    bRequired=false;
                }
            }
        });
        return bRequired;
      }
    }
},

Extracting the idea you gave me, this is what I have left:

"3_nombre_prop[]": {
   maxlength: 500,
   required: true,
   remote: {
       xurl: "vws/ajax_validar_rut.php?rut="+$('#'+$(this).parents('table').attr('id')+' #3_rut_prop').val();
       type: "GET",
       data: {
          ape_p: $('.3_ape_p').val(),
          ape_m: $('.3_ape_m').val()
       }
   }
},

But it tells me that I have a syntax error in the URL.

Would you have to change the type and leave it as POST to send the rut for data ?

Thankful, as always .. THANK YOU!

UPDATE

I can not believe that it was so simple, THANK YOU @Alvaro for the guide .. At the end I left it like this;

"3_nombre_prop[]": {
    maxlength: 500,
    required: true,
    remote: {
        url: "vws/ajax_valida_campos.php",
        type: "POST",
        data: {

        }
    }
},

And in ajax_valida_campos.php , I'm like this;

<?php
  // print_r($_POST);
  $n_cantidad=count($_POST);
  $bValida=false;
  if(intval($n_cantidad)>0)
      $bValida=false;
  else 
      $bValida=true;

  echo $bValida;
?>

In this way, valid when there is data and when not. Would it be correct?

GRATEFUL!

    
asked by x_Mario 17.03.2016 в 12:59
source

1 answer

0

There are two problems with the code above:

  • AJAX is an asynchronous call, but you try to use it synchronously.
  • The scope of return true or return false is not appropriate.
  • What does this mean? In the depends you make the AJAX call, which runs asynchronously while the code of depends continues and ends without having received a response (problem 1). Even if the AJAX was synchronous (not recommended) and you get to the part that returns true or false , the value that is returned is inside the function success and not within depends that would still not return anything (problem 2).

    This could be solved by making the AJAX synchronous and saving the value in a variable that would be returned in depends , but it is not the best option. Instead, you should use the internal jQuery Validate method: remote .

    remote requests validation of the field to a remote resource using AJAX. It's basically the same thing you're trying to do, but already integrated with the plugin, so you'll save yourself headaches and problems like the ones above.

    As you can see in the link above, the syntax of remote is very simple and similar to the AJAX in jQuery, so you almost have it all. In your particular case it would be something like this:

      

    Note: The following code has not been tested and may contain errors, the idea is to serve as a reference to support and complete it.

    rules: {
        "3_nombre[]": {
            maxlength: 500,
            required: true,
            remote: {
                url: "vws/ajax_validar_rut.php",
                type: "get",
                data: {
                    rut: $('#' + $(this).parents('table').attr('id') + ' #3_rut_prop').val(),
                    rut3: $('.3_rut').val(),
                    ape_p: $('.3_ape_p').val(),
                    ape_m: $('.3_ape_m').val()
                }
            }
        }
    }
    

    The idea is that you pass all the necessary parameters to the service that checks if the rut is correct and all the operations will be performed there, returning true if it is valid or false if it is invalid.

        
    answered by 17.03.2016 / 13:58
    source