Variable Problem
Variable Problem
(OP)
I've been working on this for a week or so now and I admit I am a little new to this. I need to be able to pull information (that works), store the information in a global variable (not sure if it is global?), use the global variable throughout the page. It will show in the first section but not in the second. Thanks in advance, I would apprecaite any help anyone could offer.
Rudy
Rudy
CODE -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> <script>jQuery(document).ready(function($) { $.ajax({ url : "http://api.wunderground.com/api/fee47ffeca88d616/geolookup/conditions/q/VA/Yorktown.json", dataType : "jsonp", success : function(parsed_json) { var location = parsed_json['location']['city']; var temp_f = parsed_json['current_observation']['temp_f']; var tempout = temp_f; //document.write ("Current temperature in " + location + " is: " + temp_f); //It will show here } }); }); </script> </head> <body> <script>document.write ("Current temperature in " + location + " is: " + temp_f); //But not show here </script> </body> </html>
RE: Variable Problem
You can use document.write() only while the document is being rendered. Your AJAX call will be executed after the document was closed. Calling document.write() that time will forcefully open the document again, discarding its current content. Use DOM manipulation instead to display new content.
And no, variables declared with the var keyword inside a function ( or any block ) are not global, but local to the given block.
Feherke.
feherke.ga
RE: Variable Problem
Thanks again,
Rudy
RE: Variable Problem
That part is simple :
CODE --> JavaScript
Feherke.
feherke.ga
RE: Variable Problem
Rudy
RE: Variable Problem
"Later" is unpredictable. I suppose the problem is you are not using it later enough. I mean, the AJAX request has to complete first to have proper values in you global variables. Otherwise they will still have their initial values ( in this case undefined as I not assigned anything specific to them on declaration ).
For more advices on what to do we will need to see your actual code.
Feherke.
feherke.ga
RE: Variable Problem
CODE -->
Thanks!
Rudy
RE: Variable Problem
Yepp, the problem is what I mentioned earlier.
The JavaScript code is executed when the surrounding script tag is closed. However all the code in your first script tag does is setting up an event handler which be called when the entire document's rendering was done.
The simplest is to move the chart rendering code inside the success event handler, so it gets executed if and when the AJAX request was completed :
CODE --> HTML
Feherke.
feherke.ga
RE: Variable Problem
Rudy