views:

75

answers:

2

Hi all,

Sorry if this question is duplicated but I couldn't solve my problem from other solutions.

I've got this code in a sepate file included in my main index:

var getSuggestedData = {    
serviceURL: $("input[name=suggestedServices]").val(), 
dataR:"",  
doRequest:function(){
 //request data to controller
 $.ajax({
  url:this.serviceURL,
  success:function(msg){    
   this.dataR = msg;    
  }   
 })     
}

}

When I'm trying to get the variable "dataR" from my index this way it's UNDEFINED! PLEASE, can someone help me out?

$().ready(function() {
getSuggestedData.doRequest(); 
alert(getSuggestedData.dataR);

});

Thank you in advance!

A: 

The reason you are not able to access the dataR object is because it is not in the same context as the result returned from the success method.

One technique is to hold a reference to this in a variable as shown below:

var self = this;

using the jquery library!
    $(this.button).bind('click',{self:this},function(event) 
    {
        var that = event.data.self;
        alert(that.num);

    });

You can also check out the post below in which I explained in detailed about the "this" keyword.

http://azamsharp.com/Posts/57%5FI%5Fmean%5F%5Fthis%5F%5Fnot%5F%5Fthis%5F.aspx

azamsharp
Hi, sorry but I don't understand completely your suggestion. Can you see my code and explain me what I am doing wrong? If I alert this.dataR within the success function I get the correct value, but if I try to do that somewhere else I can't get that value... what should I do? Thank you.
Teknotica
Try out the approach suggested by meder and let us know!
azamsharp
A: 

If memory serves me right...

this.dataR = msg;

probably needs to be

getSuggestedData.dataR = msg

the 'this' reference would be to the object fed to jQuery, you need to reference the original object. I forget if you could access it by its name directly such as this or if you need to use another method, let me know if it doesn't work out though.

meder
Hi Meder,I tried your way and the result is the same. I tried then printing the result in a textfield and as I thought, when I alert the variable the values has not been assigned yet and is empty... so, what you recommend? Thanks!
Teknotica
Can you update your description with your new code? What happens if you do alert( getSuggestedData ) inside of the callback function?
meder
Also, you should be doing $(function() { /* code */ }); , the standard convention.
meder