0

I have a ajax function that validate a textbox on my page, then I need to do something with that value (search in database and display the results on textbox). and then, I need the validation function for another function different. so..

        function validarRut(textBox) {
        var resultado;
        $.ajax({
            type: "POST",
            url: "AgendarInduccion.aspx/validarRut",
            data: "{rut:" + JSON.stringify(textBox) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function(response){
                alert("valido");
            },
            failure: function (response) {
                alert("ERROR");
            }
        });

    }

that is the validate function (works!): and the function to search in database:

 function buscarEmpresa(textBox) {
        var res;
        res = validarRut(textBox.value); // I need the result, to works with this function.!


        alert("VALOR" + res);
        if (res) {
            var resultado;
            $.ajax({
                type: "POST",
                url: "/AgendarInduccion.aspx/buscarEmpresa",
                data: "{RutEmpresa:" + JSON.stringify(textBox.value) + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: function (response) {
                    resultado = response.d;
                    var nombre = resultado[0];
                    var razonSocial = resultado[1];
                    var direccion = resultado[2];
                    if (nombre == "nulo") {
                        alert("El Rut de la Empresa No se ha Encontrado en Nuestra Base de Datos, favor de ingresar!");
                        // crear empresa!
                        // la institucion no existe; se debe crear una!
                        //btGuardar.Visible = true;
                        //btCancelar.Visible = true;

                        //txtRutEmpresa.Enabled = false;
                        //txtNombreEmpresa.Enabled = true;
                        //txtRazonSocial.Enabled = true;
                        //txtDireccion.Enabled = true;
                        document.getElementById('<%= txtRutEmpresa.ClientID %>').disabled = true;
                        document.getElementById('<%= txtNombreEmpresa.ClientID %>').disabled = false;
                        document.getElementById('<%= txtRazonSocial.ClientID %>').disabled = false;
                        document.getElementById('<%= txtDireccion.ClientID %>').disabled = false;

                        $('#<%= txtRazonSocial.ClientID%>').val(razonSocial); //razon social desde SII

                        document.getElementById('<%=btGuardar.ClientID %>').style.display = 'inline';
                        document.getElementById('<%=btCancelar.ClientID %>').style.display = 'inline';
                        document.getElementById('<%=btActualizar.ClientID %>').style.display = 'none';




                    } else {
                        $('#<%= txtNombreEmpresa.ClientID%>').val(nombre);
                        $('#<%= txtRazonSocial.ClientID%>').val(razonSocial);
                        $('#<%= txtDireccion.ClientID%>').val(direccion);
                    }
                },
                failure: function () {
                    alert('No Realizado.');
                }

            });
        }
    }

And I have a Third function that use "function validarRut(textBox)"; so I dont want to put the search function in the success, because I need to re-use the function. Any helps? PD: async: false is not a option for me.

Shock
  • 15
  • 4
  • `success: function(response){ buscarEmpresa(textBox) },` – mplungjan Jan 19 '18 at 14:27
  • If async:false is NOT an option why do you use it? – Manuel Graf Jan 19 '18 at 14:29
  • because I was testing, but is a bad solution; sorry for uncommented – Shock Jan 19 '18 at 14:31
  • @mplungjan if I use that in validarRut(textBox); i cant reuse with another function different to buscarEmpresa(textBox) – Shock Jan 19 '18 at 14:33
  • `function validarRut(textBox,search) { var callSearch = search;` and `success: function(response){ if (search) buscarEmpresa(textBox) },` - now you can do `validarRut(textBox,true)` to search or `validarRut(textBox)` to not – mplungjan Jan 19 '18 at 14:35
  • I get your solution, but in my TextBox I put onblur="javascript:validarRut(this,search )" ; how can I put a string to search ? (search = "Empresa") doesnt work – Shock Jan 19 '18 at 14:45
  • I think a Promise is best practise here. see my answer below. – Manuel Graf Jan 19 '18 at 15:28
  • Just use textbox.value consistently: `data = {}; data[textbox.name]=texbox.value;....data: data,` – mplungjan Jan 19 '18 at 15:32

2 Answers2

1

Here is my solution!, thanks a lot

    function buscarEmpresaPromise(textBox) {
        var res;
        validarRutPromise(textBox.value).then(function (res) {
            if (res.d) {
                alert(">hola");
                alert("Rut validado CORRECTAMENTE");
            } else {
                alert("Rut invalido, vuelva a ingresar porfavor: " + textBox.value);

            }
        })
        }

and the other code, that is validating True or False:

    function validarRutPromise(textBox) {
        var promise = new Promise(function (resolve, reject) {
            $.ajax({
                type: "Post",
                url: "AgendarInduccion.aspx/validarRut",
                data: "{rut:" + JSON.stringify(textBox) + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                complete: function (response) {
                    resolve(response);
                },
                fail: function (response) {
                    reject(response);
                }
            });
        })
        return promise;
    }
Shock
  • 15
  • 4
0

If I get your roblem correctly, Promises will solve your problem.

basically, your method has to return a Promise OBject. With those, you can call then(), which gets executed as soon as the Promise is resolved (success) or rejected(error)

so basically your code has to work like that:

 function validarRut(value) {
  return new Promise(resolve, reject){
    $.ajax({
      type: "get",
      url: "/",
      success: function (response) {
        resolve(response); // when this is called, every then() function gets executed
      },
      failure: function (response) {
        reject(response); // when this is called, every catch() function gets executed
      }
  });
  }

}

function buscarEmpresa(textBox) {
  var res;
  validarRut(textBox.value).then(function (res) {
    // res is whatever you passed the resolve function
    if (res) {
      textbox.text(res.toString());
      // do whatever you want with the result
    }
  })
  .catch(error){
    // error is whatever you passed the reject function
  }
}

$(document).ready(() => {
  buscarEmpresa($('#result'));
})

watch it in action: https://jsfiddle.net/yygggbsa/

Promises are the way to go for such async calls. But remember that they are unavailable in IE11:

https://caniuse.com/#feat=promises

so if you need support for older browsers like IE11, you will need to add an external library.

Further Reading:

use Promises in IE11: How to make promises work in IE11

Promises at MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Manuel Graf
  • 462
  • 5
  • 20
  • very constructive criticism there. Not. PLONK. (if you don't kn ow what it means, google it.) – Manuel Graf Jan 19 '18 at 15:07
  • Just a good advice. You had a very good chance to be merciless voted down beyond recovery – mplungjan Jan 19 '18 at 15:21
  • Is the stackoverflow community really that toxic? I just wanted to let OP know that I am working on a fiddle... quite frankly If I got voted down I wouldn't really care. As you can see I am not that desperate for reputation. I want to help and I know my solution is right, if others beg to differ, feel free. – Manuel Graf Jan 19 '18 at 15:27
  • Just don't post empty answers. Who knows when you will return or give up. Please read this and its duplicates: https://meta.stackoverflow.com/questions/269993/placeholder-answers-will-update-with-answer-soon – mplungjan Jan 19 '18 at 15:28
  • 1
    Hah. Thanks for the advice. I understand that now, but it doesn't hold for me as I am always resolving my Promises (pun strongly intended). – Manuel Graf Jan 19 '18 at 15:32
  • @ManuelGraf Hi, first thank for your attention and your patience; I have two question about your answer; First: `$(document).ready(() => { buscarEmpresa($('#result')); }) ` What mean that? Second: Doesnt work, it said in Chrome: `Cannot read property 'then' of undefined at buscarEmpresaPromise (AgendarInduccion:37) at HTMLInputElement.onblur (AgendarInduccion:186) buscarEmpresaPromise @ AgendarInduccion:37 onblur @ AgendarInduccion:186 ` I think that the code doesnt wait the respond, and then is undefined – Shock Jan 19 '18 at 15:46
  • The document ready is only for the fiddle to work and to call buscarEmpresa(). – Manuel Graf Jan 19 '18 at 16:12
  • You can only call .then() on a Promise Object. your Promise seems to be undefined. This can happen if your chrome version is below v49 (Promise() doesnt exist) or your function validarRut() is not RETURNING the Promise. look at the last line of my validarRut() function. It says return promise, so you can use validarRut(textBox.value).then(...). in your case, you would have to call buscarEmpresa() on your Blur event like $('#myTextBox').blur(buscarEmpresa). It's kinda hard to see the error without seeing the actual code. Maybe create a fiddle or codepen of your current code and post it here – Manuel Graf Jan 19 '18 at 16:23
  • Im getting the solution, but I see that new promise() required a function; and my visual studio doesnt recognize $(document).ready(() =>{; thats it the problem I think; Here is my code: https://jsfiddle.net/8j27njuh/ – Shock Jan 19 '18 at 17:10
  • `var promise = new Promise();` @ManuelGraf, i think that line need a function ? I can load my page, and return me true or false in the inspection ->network; but the promise isnt resolve – Shock Jan 19 '18 at 17:52
  • normally you dont have to declare the function within the Promise() constructor. But I updated your fiddle so it works. You can declare your ajax call within the constructor: https://jsfiddle.net/8j27njuh/1/ I also changed URL, content type etc of the ajax call so the fiddle works. – Manuel Graf Jan 22 '18 at 11:14
  • I see you found this problem yourself. Please mark my answer as the correct solution ;) – Manuel Graf Jan 22 '18 at 11:16