Can not read property 'length' of undefined

0

shows me this error in console Can not read property 'length' of undefined. My scripts are the following:

function SendZip(){
var result;
jQuery(document).on('submit','#form_zip',function(event){
    if($("#code").val()==""){
        event.preventDefault();
        $(".control-label").css({"color":"red"});
    } else {
        event.preventDefault();
        jQuery.ajax({
            url:'ajax.php?mode=zip',
            type: 'POST',
            dataType: 'json',
            data: $(this).serialize(),
            beforeSend: function(){
                $("#loading").html('<img style="width: 100%; display: none;" src="assets/img/loading.gif">');
                $("#submit-zip").text("Sending");
                $("#submit-zip").attr("disabled", "disabled");
            }
        })

        .done(function(res){
            if(res.r == false){
                result = '<div class="alert alert-danger alert-fill alert-close alert-dismissible fade in" role="alert">';
      result += '<center><h3>The area code is not valid</h3></center></div>';
                $("#loading").html(result);
            }else{
                //Aqui el error for(var i=0; i<res.datos.length; i++){
                    var zip_code = res.datos[i].id_code;
                }
                setTimeout(function(){
                    $("#loading").hide();
                },2000);
                window.location='encuesta.php?code='+zip_code+'';
            }
        })
    }
});
}

php:

<?php

     if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
 strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
     include 'class.Conexion.php';
     $db = new Conexion();

 $code = $_POST['code_z'];

 $sql = $db->prepare("SELECT * FROM codes WHERE zip_code = ? LIMIT 1");
 $sql->execute(array($code));
  if($sql->rowCount()>0){
   $rows[] = $sql->fetch();
   echo json_encode(array('datos'=>$rows));
  }else{
   echo json_encode(array('r'=>false, 'mensaje'=>$sql->errorInfo()[2]));
  }
 }else{
   header('location:index.php');
     }
?>

The json that I get is of this type:

 0:"1"
 1:"32003"
 2:"Fleming Island"
 city:"Fleming Island"
 id_code:"1"
 zip_code:"32003"
    
asked by Alejo Mendoza 21.03.2018 в 20:37
source

0 answers