jquery - javascript - set var equal to data returned from a function -
var ipaddress="unknown"; $.getjson('http://jsonip.appspot.com/?callback=?', function(data){ ipaddress=data.ip;}); document.getelementbyid('callbackform').elements["callback_form.ipaddress"].value = ipaddress;
this javascript code sets var ipaddress equal 'unknown', executes jquery function sets value of ipaddress user's ip. attempt set form element equal value of ipaddress.
this not working. form element being set 'unknown'. i'm not sure if scoping problem? advice appreciated.
what's happening callback executing asynchronously. $.getjson
call tells browser "go off , data url; when it's ready, call function i've provided". function doesn't execute right away.
you can either move more logic callback (i.e. inline ipaddress var , assign form element in callback), or switch more full-featured jquery.ajax
method , pass async:false
in option set. of course, in cases you'll waiting network before rest of call executes.
Comments
Post a Comment