does not enter if in javascript - ajax

1

I have an ajax script which goes and queries a mysql DB in a php, if there is a record I return an echo "yes"; and if not "no";

here the file delete_radio_per_serial.php

<?php
//Configuracion de la conexion a base de datos
$link = mysql_connect('localhost', 'wiilson', 'Wilson.456*') or die('No se pudo conectar: ' . mysql_error());
//echo 'Connected successfully';
mysql_select_db('sqlcomunicaciones') or die('No se pudo seleccionar la base de datos');

//variables POST  
  $serial=$_POST['serial'];   

$total = mysql_num_rows(mysql_query("SELECT * FROM dispositivos WHERE serie ='$serial'"));
if($total==0)
{
    echo "no";
}
else
{
  $sql=mysql_query("DELETE FROM dispositivos WHERE serie ='$serial'");
  echo "si"; 
}
// Liberar resultados
mysql_free_result($sql);
// Cerrar la conexión
mysql_close($link);
?>

This or not I keep it in a variable resp where I want to evaluate if it is a yes to do a few things later or if it is a no also, the problem is that it does not enter the if, if I print the answer in an alert before to enter the if, if it prints well, I get it yes or no, but the alert (which test use) inside the if, does not execute them

here the ajax script

function objetoAjax(){
  var xmlhttp=false;
      try 
      {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      } 
      catch (e) 
      { 
        try 
        {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }  
        catch (E) 
        {
        xmlhttp = false;
        }
      }
      if(!xmlhttp && typeof XMLHttpRequest!='undefined') 
      {
      xmlhttp = new XMLHttpRequest();
      }
      return xmlhttp;
}

//Función para recoger los datos del formulario y enviarlos por post  
function continuar_eliminar()
{
  var serial_digitado=document.getElementById('input_serial').value;  
  if(serial_digitado=="")
  {
          alert('Debe digitar el serial del radio a eliminar');
          location.reload(true);
  }
  else
  {
    var desicion = confirm("¿Esta seguro?");
    if (desicion == true)
    {
      var serial=document.getElementById("input_serial").value;
    }
    else
    {
      location.reload(true);
    }
  }

  //div donde se mostrará lo resultados
  divResultado = document.getElementById('resultado');

  //instanciamos el objetoAjax
  ajax=objetoAjax(); 
  //uso del medotod POST
  //archivo que realizará la operacion
  //eliminar_radio_por_serial.php
  ajax.open("POST", "eliminar_radio_por_serial.php",true);
  //cuando el objeto XMLHttpRequest cambia de estado, la función se inicia
  ajax.onreadystatechange=function() 
  {
    if (ajax.readyState==4) {
      //mostrar resultados en esta capa
    divResultado.innerHTML = ajax.responseText

    //guardo si o no aqui en la variable resp
    var resp=ajax.responseText;

    // como prueba, imprimo el resultado y si funciona efectivamente
    alert(resp);

    if(resp=="si")  //aqui ya probé con ===
      {
        //aqui al if donde no entra
        alert('si hay registros');
      }
    if(resp=="no")
      {
        //a este tampoco
        alert('no hay registros');
      }
    }
  }
    //LimpiarCampos(); 
  ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  //enviando los valores a registro.php para que inserte los datos
  ajax.send("serial="+serial)
}
    
asked by Gabriel Uribe Gomez 19.09.2017 в 23:35
source

2 answers

1

Good afternoon, I had the same problem as you, I made the request to the server, this returned a string, then I compared it in javascript and it did not work haha.

I solved it changing in my file PHP , where I make the request to the server, that I return a array with json_encode instead of the string alone. In your code PHP would be as follows.

$total = mysql_num_rows(mysql_query("SELECT * FROM dispositivos WHERE serie ='$serial'"));
if($total==0)
{
        $error = ['No'];
	$arrayJson = json_encode($error);
	print_r($arrayJson);
}
else
{
	$sql=mysql_query("DELETE FROM dispositivos WHERE serie ='$serial'");
	$error = ['Si'];
	$arrayJson = json_encode($error);
	print_r($arrayJson);
}

Now in your javascript code you only have to "go through" the array that returns the request AJAX and then yes, compare it.

I used JQuery a each to go through it. I hope my answer will help you.

    
answered by 20.09.2017 в 00:08
1

Sometimes the responseText of Ajax comes with an additional line break. What can that be? The reasons are diverse and may even vary depending on the server or the PHP version.

To try to avoid this, it is best not to leave line breaks or blank spaces before the closing tag ( ?> ) of the PHP script that sends the response to Ajax.

Anyway, it does not hurt to clean up the response of responseText using trim() which:

  

Eliminate blank spaces at both ends of the string. The   blank spaces in this context, are all characters without   content (space, tabulation, etc.) and all new characters   lines (LF, CR, etc.).

You can see all the details in the MDN documentation .

Then, doing this:

var resp=ajax.responseText.trim();

Your variable resp will be saved free of these spaces or blank characters left over and the comparison will not fail.

By the way, check the PHP code, so that there are no blank lines before the closing tag.

    
answered by 21.09.2017 в 16:11