2

As the title says, I'm trying to populate the properties of an object using jQuery-Ajax. I've been trying to find the right way to do it for hours, but couldn't make it work...

This is my code:

function Persona(){
    this.nombre;
    this.apellido;
    this.buscarNombre= function(callback){
    $.get("nombre.php", function(datos){
        datos = eval("(" + datos + ")");
        this.nombre = datos.nombre;
        this.apellido = datos.apellido;
        alert(this.nombre);
      })
    };
}

$(document).ready(function(){
       var pp = new Persona();
       alert(pp.nombre);

}

I think the problem is the scope of the function that retrieves the data from the server it's different from the scope of the object, but I don't realize how to pass the data from one place to the other...

The data is arriving perfectly from the web server... I used FireBug to be sure...

Thanks in advance!

1
  • do you need to call the actual function? pp.buscarNombre();? Commented Sep 30, 2011 at 14:20

1 Answer 1

3

if you replace alert(pp.nombre); with pp.buscarNombre();. You will get the desired results. And your this reference is wrong:

function Persona(){
    var self = this;    
    this.nombre;
    this.apellido;

    this.buscarNombre= function(callback){
        $.get("nombre.php", function(datos){
            datos = eval("(" + datos + ")");
            self.nombre = datos.nombre;
            self.apellido = datos.apellido;
            alert(self.nombre);
        })
    }
}

$(document).ready(function(){
       var pp = new Persona();
       pp.buscarNombre();    
}
Sign up to request clarification or add additional context in comments.

Comments

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.