Jaime Quintana Jaime Quintana - 6 months ago 20
Javascript Question

IF condition with AJAX response or AJAX response.response.Text is not working

I am developing a web page which displays an alert as soon as somebody inserts a new tuple in a database table using the same

'mesa'
column that I sent in my AJAX request, so for that purpose I created a Javascript Timer in which I am constantly sending AJAX requests to check if there is a new tuple in my database table and so far the timed AJAX request are working, but when I want to condition the response with an
if
to see if the value of it equals to a certain value, it just completely skips it, so I am unable to display alerts even if the values that the AJAX response requests are throwing are right, so I was wondering what I could be doing wrong, I have been analyzing the code for over 2 hours and I don't seem to find the error, I even displayed alerts to verify that the
response
is equal to 0 or 1 which showed up that they do display them right, and I used
response.responseText
too , any help would he highly appreciated, thank you so much.

This is my Javascript file

var Solicitud_Comandas = [];


for (var k = 1; k <= 15; k++) {
Solicitud_Comandas[k] = SolicitudComanda(k);

if(!sessionStorage.getItem("rm"+k))
{
sessionStorage.setItem("rm"+k,false);
}
}

function SolicitudComanda(k)
{
return function() {
$(document).ready(function()
{
$.ajax({
type: "POST",
url: "Consultar_Comandas_Pendientes.php",
data: {mesa : k},
complete: function (response, TextStatus)
{
MensajeAlerta(response,k);
},
fail: function (resultado,TextStatus)
{
alert("it didn't work because... " + resultado+ " " +TextStatus);
}
});
});
}
}

function MensajeAlerta(response,m)
{


if(response == 0 )
{
sessionStorage.removeItem("rm"+m);
sessionStorage.setItem("rm"+m,false);
}
else if (response == 1)
{
if(sessionStorage.getItem("rm"+m) == "false")
{
alert("Hay una comanda pendiente en la mesa "+m);
sessionStorage.removeItem("rm"+m);
sessionStorage.setItem("rm"+m, true);
}
}
}

Temporizador= setInterval(SolicitudDeComanda,2500);

function SolicitudDeComanda()
{

$(document).ready(function(){

for (var l =1; l<= 15; l++) {
Solicitud_Comandas[l]();
};

});

}


And this is the Consultar_Comandas_Pendientes.php

<?php
require "Conexion.php";
$NumeroMesa = $_POST["mesa"];
$Platillos = 0;
$filas = false;
$SelectionRows = "SELECT * FROM comandapendiente WHERE mesa = '$NumeroMesa'";
$rows = mysqli_query($con,$SelectionRows);
while($reg = mysqli_fetch_array($rows))
{

if(isset($reg["id"]))
{
$filas = true;
$Platillos++;
}
}


if ($filas == true)
{

echo true;
}
else
{
echo false;
}

mysqli_close($con);
?>


As you can see, if there is a new tuple, the AJAX response is going to be equal to either
true
or
false
which is what I question on the
if
statements in the Javascript code.

Answer

The first issue you have is caused by using the $.ajax({ ... complete: property and assuming the first argument to the callback is your data. But it is not, it is the request object (see documentation). Use success: instead of complete: and then you get the data as first argument to your callback function.

The second issue you have is caused by the PHP line:

echo false;

This does not echo anything, because in PHP when false needs to be converted to string, it becomes the empty string, unlike in other languages, where it becomes "0" or "false".

So you should better echo literal strings in PHP, like:

echo "1";

and

echo "0";

Also, make sure PHP does not output anything else than just that 0 or 1. Specifically check that there are no blanks, tabs, empty lines... etc, before the <?php tag or after the ?> tag. If you have several such opening and closing tags, try to join them into one PHP block.

For the same reason, make sure to save your PHP in UTF-8 without BOM. The Byte Order Mark is a three character sequence that is sometimes saved at the start of a file, in order to declare the character encoding as UTF-8. But this sequence would then also be part of the response. Most editors have an option to save with or without BOM.

Some remarks on your code

It is a bit strange to see $(document).ready(...) inside other functions. Although this works fine, it is not usually done this way. Normally there is no reason to have it inside another function. All is OK, if you use it once, at this position only:

$(document).ready(function(){
    Temporizador= setInterval(SolicitudDeComanda,2500);
});

I would write false as a string when writing to local storage:

sessionStorage.setItem("rm"+k, "false");

It works fine without the quotes, but you then rely on the fact that JavaScript converts it to that string. I believe your code looks better with "false" written as a string explicitly.

Also, it seems unnecessary to call removeItem() if you are doing a setItem() right after it. setItem() overwrites any existing value with the same key.

In your tests on the response data, it would make more sense to do string comparisons, since the data returned by PHP will be string. So like:

if(response == "0")

... and add an else to catch any unexpected value (other than "0" or "1") so you are made aware of it (via alert or something).

If you have trouble with some unexpected characters preceding the value 0 or 1, and you can't get rid of those by removing the BOM and any white space in your PHP file, then there is a work-around by relaxing your test like this:

if (response.indexOf('0') !== -1) 

It is also better to specify the dataType: 'text' option in your ajax call, so not to leave that to jQuery to guess.