-1

I'm developing an application that needs to check if a product exists, so I chose Jquery beacuse It's really easy to use but I'm having some troubles checking if a product exists or not

I have a table with one sigle row and inputs on its td tags and iT works this way; You type the code of product and press ENTERto check if exists or not, if It is, It should show an alert saying "EXISTS" and if It's not, an alert saying "NOT EXIST". I already have a product registered wich code is "ioi909090io", so when I press ENTER says "NOT EXISTS" but then shows php output wich is 1 beacuse if the product exists php do "echo true;", so php said yes and jquery said no. For you to understand better I share you the code.

My table in html with inputs:

<table class="table table-bordered">
    <thead>
        <tr>
            <th>Codigo</th>
            <th>Descripción</th>
            <th>Unidades</th>
            <th>Precio</th>
            <th></th>
        </tr>
    </thead>
    <tbody id="tblsurtir">
        <tr class="parenttr">
            <td width="20%"> 
            <input type="text" class="form-control input-sm codigop" value="ioi909090io"> 
            </td>
            <td>
            <input class="form-control input-sm campossurtir campossurtirdescr" disabled>
            </td>
            <td width="10%">
            <input type="text" class="form-control input-sm campossurtir campossurtirunidades" disabled>
            </td>
            <td width="10%">
            <input type="text" class="form-control input-sm campossurtir campossurtirprecio" disabled>
            </td>
            <td width="5%">
            <button class="btn btn-danger btn-xs deleterowproduct" data-toggle="tooltip" data-placement="right" title="Borrar"><span class="glyphicon glyphicon-minus"></span></button>
            </td>
          </tr>
         </tbody>
</table>

My Js file:

function comprobarExistencia() {
//this variable is the code of the product that i want to check 
 var codigoSeleccionado = document.activeElement.value;
    $.ajax({
        type: "POST",
        url: "PeticionesAjax.php",
        data: { codigoSeleccionado: codigoSeleccionado, action: "checkprodexists" },
        success: function(data) { 
            alert(data); //this line print data and it show 1
            return true; //this suppossed to return true
         } })
    .done(function(data) { alert(data.slice(0, 100)); }) //it says 1 too obviously
    .fail(function() {  })
    .always(function() {  });
}

And my php file that process ajax:

<?php 

require_once "core/init.php";

if (Ajax::exists()) {
 $almacen = new Almacen(new DB);
 switch (Input::get("action")) {        
    case 'checkprodexists': 
    $prod = $almacen->prodExists(Input::get("codigoSeleccionado"));
    if ($prod){ 
    //this is the 1 that appears on message 
        echo true;
    }else {
        echo false;
    }
    break;
    case 'newprod':         
    $nvoprod = $almacen->newProd(array(Input::get("codigoactual"),
                                           Input::get("newDescr"),
                                           Input::get("newUnidades"),
                                           Input::get("newPrecio")));
    if ($nvoprod) {
    echo true;
    }else {
    echo false;
    }
    break;
    default:
    echo "ERROR";
    break;
    }
}

?>

back in my Js file I have this:

$(document).keypress(function(e){
    //this line detect when the input wich contains the code of product is "submited"
    if (e.which == 13 && $(".codigop").is(":focus")) {
        //var codigoSeleccionadoid = document.activeElement.id;
        if(validarCodigo()) { //this only validate if the code has the right format

        //NOW THIS LINE IT'S DRIVING ME CRAZY
        //this function suppossed to return true beacuse product exists but that not happening
        if(comprobarExistencia()) { 
                alert("EXISTS");
            }else {
        //this is the message that it shows     
                alert("NOT EXISTS");
            }
        }else {
            alert("formato invalido");
        }
    }
});

so now I'm lost, I don't really understand what's wrong maybe It's just a little thing that I missed, I hope you guys can help me.

DaveSanchez
  • 329
  • 1
  • 3
  • 10
  • 1
    You can't `return` from an AJAX call. – tymeJV Sep 15 '14 at 01:40
  • You do realize that `comprobarExistencia` doesn't return anything? – Musa Sep 15 '14 at 01:41
  • 1
    @Musa no, likely the user does not. – Charlie Schliesser Sep 15 '14 at 01:42
  • so return true in success function isn´t returning anything, i didn't knew that, sorry jquery and ajax are new stuffs for me, if i write a function called "yes" that only return true and call it on success function, will it work? or, what should i do? – DaveSanchez Sep 15 '14 at 01:47
  • Yes, calling a function in your success handler will do what you're looking to do. But I really recommend reading the top-voted answer in the link I posted below. You'll really be glad you did! – Charlie Schliesser Sep 15 '14 at 01:49

1 Answers1

1

You need to understand function scope. The return true; line is indeed returning true, but the outer function (comprobarExistencia) isn't returning anything explicitly, thus it simply returns undefined. Your success: function()... line is really just another function. So, in this success handler, call another function to do what you want with the return value.

A great example of this same problem can be found at: How do I return the response from an asynchronous call?

At the core of this problem is understanding asynchronous javascript (or asynchronous programming concepts in general).

Community
  • 1
  • 1
Charlie Schliesser
  • 7,851
  • 4
  • 46
  • 76
  • Might want to mention callbacks...or just give a quick example. Either way, +1 for the core problem. – tymeJV Sep 15 '14 at 02:19