IF conditional on jQuery

1

Good morning,

The purpose of this code is to check if a record (number), sent through the form, exists in the database. The submit button (which is invisible) must be displayed on screen if it is confirmed that the record entered exists in the database.

It happens that the input submit disappears from the screen only when a record is entered in the input text and then it is deleted.

I do not understand why the conditional of this jQuery code does not apply as I think it should.

The code is divided into 2 files.

File 1 - JAVASCRIPT + HTML:

$(document).ready(function() {

document.seleccionar.modificar.style.visibility = "hidden";
                         
      var consulta;
             
      $("#id").focus();
                                                 
      $("#id").keyup(function(e){
             
             consulta = $("#id").val();
                                      
             $("#resultado").delay(100).queue(function(n) {      
                                           
                  $("#resultado").html('<img src="imagenes/loading/ajax-loader.gif" />');
                                           
                        $.ajax({
                              type: "POST",
                              url: "comprobar.php",
                              data: "b="+consulta,
                              dataType: "html",
                              error: function(){
                                    alert("Error petición ajax");
                              },
                              
success: function(data){  
						  
$("#resultado").html(data);								
n();
						  
if (data == 1){
document.seleccionar.modificar.style.visibility = "visible"; 
}
}
                  });
                                           
             });
                                
      });
                          
});

-------------------------------------------------------------

<form name="seleccionar" id="seleccionar" action="modificar.php" method="post">
   	<input type="int" required id="id" name="id" placeholder="Introduce ID..." value="" />
	<span id="resultado"></span>
    <input type="submit" id="modificar" name="modificar" value="Modificar" /><br><br/>		
</form>

File 2 - PHP:

<?php
      $user = $_POST['b'];
       
      if(!empty($user)) {
            comprobar($user);
      }
       
      function comprobar($b) {
			
			include("conexion_db.php");
			
			$query = mysqli_query($conexion, "SELECT * FROM formulario WHERE id = '".$b."'");        
			
            $contar = mysqli_num_rows($query);
			             
            if($contar == 0){
                  echo "<span><img src=\"imagenes\web\action_delete.png\"></span>"; 			
            }else{
                  echo "<span><img src=\"imagenes\web\action_check.png\"></span>";
            }
			
			echo json_encode($contar);
      }     
?>

I would appreciate if someone could tell me why the input submit is not displayed when the condition is executed. Thanks in advance.

    
asked by Joel 30.08.2017 в 05:00
source

2 answers

3

EDIT

I have reproduced the scenario and the code works, except in cases where I entered the 0 value in the input or when it remained blank. The reason is that, in the old PHP code, in those cases an invalid JSON object was created and the Ajax request returned a parse error . To avoid this, I have improved the PHP code, forcing it to always create a valid json. You will see that, if no values are produced, the PHP code will return a json with the values set to null . You can change those values for others, which can be used to manage nulls. It is something that is not thought, however, the user can enter anything in the input and must be handled properly.

I have also improved the way to obtain the values of the json object, using: data.img and data.contar .

In the HTML part I have dedicated a div to the image, because in the tests, the image was placed on top of the input , when I was putting it in the same element. You can ignore that change if you wish so.

My console.log throws data like these:

{contar: "1", img: "action_check.png"}

Or:

{contar: "0", img: "action_delete.png"}

Or, when you enter 0 in the input or leave it blank:

{contar: null, img: null}

And it shows test images that I have put for each case.

If it does not work for you, then it would be a file path problem that you put in the url of the Ajax request or for something other than the code.

Below, I leave the modified code.

Once an answer has been drafted, I will allow myself to make some indications about the code.

  • $(document).ready(function() {... is obsolete from jQuery 3 ( see this question ). We will change it by $(function() {... .
  • Handling Ajax requests only with success: function(data){ ... is not recommended and success in turn is also obsolete. We will change it to done and we will include controlling the code in case the request fails, using fail .
  • We will apply changes using the id of the item.
  • As I said in the comments, we will do echo once with all our data and then we will read the JSON from jQuery and act accordingly. Doing this we apply a basic rule of use of jQuery / Ajax: make requests to the server in background and handle the response from the same page they were made without having to refresh. The problem of doing echo several times in PHP is that you will not have a strict control of the answer you will receive.
  • HTML / JS

    $(function() { 
    
      $("#modificar").hide();
      var consulta;
      $("#id").focus();                                                     
      $("#id").keyup(function(e){
             consulta = $("#id").val();
             $("#resultado").delay(100).queue(function(n) {       
                  $("#resultado").html('<img src="imagenes/loading/ajax-loader.gif" />');
    
                        var request = $.ajax({
                          url: "comprobar.php",
                          method: "POST",
                          data: "b="+consulta,
                          dataType: "json"
                        });
    
                        request.done(function( data ) {
                            console.log(data);
                            img=data.img;
                            contar=data.contar;
                            imagen='<img src="imagenes/web/'+img+'/">';
                            $("#imagen").html(imagen);                               
    
                            n();
    
                            if (contar == 1){
    
                                  $("#modificar").show();
    
                            }else{
    
                                  $("#modificar").hide();
    
                            }
    
                        });
    
                        request.fail(function( jqXHR, textStatus ) {
                          alert( "Error petición Ajax: " + textStatus );
                        });         
            }); 
        });    
    });
    
    <form name="seleccionar" id="seleccionar" action="modificar.php" method="post">
    <input type="int" required id="id" name="id" placeholder="Introduce ID..." value="" />
    <span id="resultado"></span>
    <input type="submit" id="modificar" name="modificar" value="Modificar" /><br><br/>  
    <div id="imagen"></div> 
    </form>
    

    PHP

    <?php
          $user = $_POST['b'];
    
          if(!empty($user)) {
    
                $datos=comprobar($user);
    
          }else{
                /*
                    *Hay que prever que no se envíen datos
                    *construir un json que sea válido
                    *los valores pueden ser otros
                */
                $datos=array("contar"=>null, "img"=>null); //Aquí puedes poner en vez de null un nombre de imagen válido: "img"=>"una_imagen.png"
    
          }
    
          /*Imprimimos el json*/
          header('Content-Type: application/json');
          echo json_encode($datos);
    
    
          function comprobar($b) {
                include("conexion_db.php");
    
               $query = mysqli_query($conexion, "SELECT * FROM formulario WHERE id = '".$b."'");        
    
               $contar = mysqli_num_rows($query);
    
               if($contar == 0){ 
    
                    $datos=array("contar"=>$contar, "img"=>"action_delete.png"); 
    
               }else{ 
    
                    $datos=array("contar"=>$contar, "img"=>"action_check.png"); 
               } 
    
               return $datos;
    
          }     
    ?>
    
      

    Note: This query "SELECT * FROM formulario WHERE id = '".$b."'" is vulnerable to SQL injection, to give security to the   code, consider the use of prepared queries:    "SELECT * FROM formulario WHERE id = ?"   passing apart the value of $b using   existing methods for this.

        
    answered by 30.08.2017 в 17:01
    0

    Good, we should see what is the functionality of the "n" function, in case you are doing something there that prevents the execution of the code from continuing.

    As a tip, you should make sure that PHP returns what you expect, for that, try the console.log ();

    My code proposal is:

    success: function(data){  
      console.log('Data que devuelves => '+data);             
      $("#resultado").html(data);                               
      n();  //Explicar que hace esta funcion??
    
      if (data == 1){
       $('#modificar').css('display','block');
      }
    }
    

    Good luck,

        
    answered by 30.08.2017 в 13:26