Im sure there is a simple solution for this but im having issues,
I have an external ajax.js file that has an AJAX call like so:
$(function() {
$.ajax({
url: url,
success: function( data, status )
above the AJAX call I have got two global variables called ticker and url like so:
var ticker = 'AAPL'
var url = 'http://blahblahblah' + ticker
In my HTML file I have got an input box where the user types in a ticker symbol (e.g. GOOG) and clicks a button that would update the ticker variable so that the AJAX call is done again with the new URL.
<form id="form">
<h3>Enter the ticker symbol of the company you wish to view:</h3>
<input type="text" id="userInput">
<button onclick="myFunction()">Try it</button>
</form>
<script type="text/javascript" src="ajax.js">
<script>
function myFunction()
{
//old value
alert(ticker);
ticker = document.getElementById('userInput').value;
//new value
alert(ticker);
}
</script>
This code changes the ticker variable but the AJAX call is still being performed with the old ticker url. I think its not being assigned properly? Im very new to AJAX but I cant find any tutorials online that explain this problem.
Thanks
Strings are immutable in Javascript, meaning that url is going to be constant, even if you change ticker. Do this instead:
$(function() {
$.ajax({
url: "http:/blah" + ticker,
success: function(data, status) {}
});
});
EDIT: Now that I think about it, it has nothing to do with strings being immutable. Doing url = "http:/" + ticker
doesn't create a closure with the value of ticker
, it simply creates a new string value and stores it in url
. After the new value is created, it's not linked to ticker
in any way.
As far as I can tell from the code you've posted, your ajax routine is only being called when the page is loaded, which explains why only the default url / ticker is shown in the results.
You need to wrap the ajax routine in a function and call it after the user has inputted a symbol:
In your ajax.js file:
function getSymbolInfo(ticker) { // consider passing ticker to this function instead of using a global var
$.ajax({
url: url + ticker,
success: function( data, status ) {
// show results
}
});
}
And from MyFunction:
function myFunction()
{
var ticker = document.getElementById('userInput').value;
getSymbolInfo(ticker);
}