Problem calling javascript function does not return result generated by ajax

0

I have a problem that I can not solve, it turns out that I want to call a function which after doing an insert in mysql returns the id, that makes it perfect, but my function never manages to receive the result despite the id by console It comes out correctly, what am I doing wrong?

Now if instead of calling the function I hit it below if doing another function walks. As it does not wait for the return of the function and continues long A thousand thanks

example console log gives me

index.php? mod = documents & new: 272 Document id undefined index.php? mod = documents & new: 305 The generated id is 12

  var idDocumento=0;

   function newfun(){
        var termino=false;                          
        idDocumento=SaveDoc();   //<-- nunca regresa el id creado no entiendo porque sale undefined
        if (idDocumento==0){
            console.log ("No pudo guarda el doc.");
        }
        else
        {
            console.log ("Documento id "+idDocumento);

            if (termino==true){
                location.reload();
            }               
        }
      }



    function SaveDoc(){

    //Grabo el documento
    var claveingresado=0;
    var  sigue=0;
    if($(seguimiento).is(':checked')){
        sigue=1;
    }

    var parametros = {
            "valorCaja1" : $('#asunto').val(),
            "valorCaja2" : $('#nota').val(),
            "valorCaja3" : sigue
    };
    $.ajax({
            data:  parametros,
            url:   'grabo-doc.php',
            type:  'post',
            beforeSend: function () {
                    $("#recargado").html("Procesando, espere por favor...");
            },
            success:  function (response) {
                    $("#recargado").html(response);
                    idDocumento=response;  //id creado
                    console.log("El id generado es "+idDocumento);        //<----- aca lo muestra perfecto
                    return idDocumento;   //<---deberia regresar ese valor
            }
    });
    }       
    
asked by Cristian 07.01.2018 в 19:12
source

2 answers

1

The problem you have is that your function SaveDoc() does not return anything and the value you need is resolved asynchronously, therefore you need to solve the problem asynchronously. You have several options, the callbacks , the promises and the observables .

  

With callbacks it would be like this:

function SaveDoc(callback) {
    // ...
    $.ajax({
        // ...
        success: function(res) {
            // ...
            callback(res);
        }
    });
}

SaveDoc((id) => {
    // Tú código...
});
  

With promises it would be like this:

function SaveDoc() {
    return new Promise((resolve, reject) => {
        // ...
        $.ajax({
            // ...
            success: function(res) {
                // ...
                resolve(res);
            }
        });
    });
}

SaveDoc().then((id) => {
    // Tú código...
});
  

With observables it would be like this:

function SaveDoc() {
    return Observable.create((observer) => {
        // ...
        $.ajax({
            // ...
            success: function(res) {
                // ...
                observer.next(res);
                observer.complete();
            }
        });
    });
}

SaveDoc().subscribe((id) => {
    // Tú código...
});

The most common option is usually the callbacks and the promises (although I'm looking for compatibility), the observables require an external library and for the problem you have, I do not think it's necessary.

    
answered by 07.01.2018 / 19:34
source
0

Denis one more question if I had to make that same call and for example pass a parameter as it would be? Assume that to run the ajax you need to receive an id to pass to the php as parameters, you could do

introducir el código aquí
    function SaveDoc(PARAMETRO,callback) {
     // ...
     $.ajax({
       // ...
     success: function(res) {
        // ...
        callback(res);
        }
      });
      }

    SaveDoc(PARAMETRO,(id) => {
          // Tú código...
      });        

Is something like this right?

    
answered by 07.01.2018 в 20:17