[jQuery] variable scope in .post

2007-01-15 Thread Dan Caragea
Hi,

I have some problems setting a global variable from within the success() 
function inside a .post.
Here is a simplified version of what I have:

function addedit() {
   var lk_id=0;
   $.ajax({url:'ajax/my_script.php',
   type:'POST',
   dataType:'html',
   data:'optype=add',
   success:function(data) {
  if (data!=null  data!='') {
   //alert(lk_id);
 lk_id=parseInt(data);
  }
}
   });
alert(lk_id);
}

My script returns a single number and I want lk_id to get that value in 
the success() function of the ajax call.
The commented alert() in the success function can read the value of the 
outer lk_id (in this case 0), lk_id is set to the new value but the last 
alert() of the function returns 0 again.
This function is called from a link with the onclick=addedit() 
attribute. I am using firefox 2
I suppose I could use the load() function to put the result in a hidden 
input, then read that input but it seems a little too complicated.

Any help regarding this problem is appreciated

-- 
Dan




___
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/


Re: [jQuery] variable scope in .post

2007-01-15 Thread Dan Caragea

Man, that was easy! Thanks for help, it works like a charm now.

Dan



Ⓙⓐⓚⓔ wrote:

your code is close, but because ajax is ASYNCHRONOUS the var gets set
after the alert is executed.

normally you would do everything that deals with the lk_id inside the
success function (or a function called from inside the success
function)


On 1/15/07, Dan Caragea [EMAIL PROTECTED] wrote:
  

Hi,

I have some problems setting a global variable from within the success()
function inside a .post.
Here is a simplified version of what I have:

function addedit() {
   var lk_id=0;
   $.ajax({url:'ajax/my_script.php',
   type:'POST',
   dataType:'html',
   data:'optype=add',
   success:function(data) {
  if (data!=null  data!='') {
   //alert(lk_id);
 lk_id=parseInt(data);
  }
}
   });
alert(lk_id);
}

My script returns a single number and I want lk_id to get that value in
the success() function of the ajax call.
The commented alert() in the success function can read the value of the
outer lk_id (in this case 0), lk_id is set to the new value but the last
alert() of the function returns 0 again.
This function is called from a link with the onclick=addedit()
attribute. I am using firefox 2
I suppose I could use the load() function to put the result in a hidden
input, then read that input but it seems a little too complicated.

Any help regarding this problem is appreciated

--
Dan




___
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/





  
___
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/