0

I have a Javascript object which has a jquery ajax call to server to fill one of its attributes:

function Busqueda(contenedor){
    var datosPost = "someData";

    var resultados = undefined;
    var that = this;

    this.buscar = function(){
         jQuery.ajax({
            type: "POST",
            dataType: "json",
            url: "phpFile.php",
            data: datosPost,
            success: function (data){
                if(data.error != 0){
                    alert(data.errorTxt);
                } else {
                    that.resultados = data.resultados;
                }
            }
        });
    }
}

The ajax call should fill the attribute "resultados". However, after the "buscar" method is run, resultados remains undefined.

Also, I debugged "that.resultados" inside the success method and it is Busqueda's attribute.

What is going on?

2 Answers 2

1

Why are you using that.resultados? do you mean "this"? It should just be "resultados"

function Busqueda(contenedor){
    var datosPost = "someData";

    var resultados = undefined;
    var that = this;

    this.buscar = function(){
         jQuery.ajax({
            type: "POST",
            dataType: "json",
            url: "phpFile.php",
            data: datosPost,
            success: function (data){
                if(data.error != 0){
                    alert(data.errorTxt);
                } else {
                    resultados = data.resultados;
                }
            }
        });
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Well, since success() is a callback, he needs to use 'that', since 'this' will be bound to the window and not to Busqueda.
resultados is not a member of the Busqueda instance. It is a private variable, accessed by simple assignment and not any this/that dereference.
Tried without this/that, but didn't work. My code was based on this article: crockford.com/javascript/private.html
0

You never show how you use it. Are you properly creating an instance?

var o = new Busqueda();
// ... after the ajax success
console.log(o.resultados)

If you don't use new then this (and that) and will be window, not o.

1 Comment

var busqueda = new Busqueda($('#busquedaPersona')); busqueda.buscar();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.