Tastybrownies
Tastybrownies

Reputation: 937

Calling a website and getting JSON information back

I am not too experienced in javascript on using API's and how to call websites and get information back. I have done this before in Java using HTTP objects and more. I am attempting to make an application where a user can type in a company stock name such as APPL and get back a ton of data like gains, losses, changes, etc. This shouldn't be that hard. I have a html/javascript file with an input textbox for the stock name. This part is easy. But after I tack on the stock name to the end of the URL by concatenation I don't know how to make the call and get the JSON information. There are examples of how to do this in other languages in the web page I am using but not for javascript. I am using this link as a tutorial:

 http://digitalpbk.com/stock/google-finance-get-stock-quote-realtime

Here is my javascript code so far: Again this is probably really simple to do. Any help on this would be greatly appreciated and is good to know in the future.

script type="text/javascript">

var submitButton = document.getElementById("submitButton");
submitButton.addEventListener('click', actionPerformed, false);

function actionPerformed(e)
{

    var textValue = document.getElementById("stockTextBox").value;
    var urlEncoded = "http://finance.google.com/finance/info?client=ig&q=NASDAQ:" + textValue.toString();


    for (var i = 0, len = urlEncoded.length; i < len; ++i) {
     var object = urlEncoded[i];
     confirm(object.toString());
 }

}


</script>

I just found the following code for using HTTP GET and tried it out but nothing happens when I click the submit button. Any suggestions on what to do or what's wrong???

 function httpGet(theUrl)
    {
    var xmlHttp = null;

    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false );
    xmlHttp.send( null );
    return xmlHttp.responseText;
    }

Wow, this is turning out to be a lot more work then I had anticipated. Here is the URL string I am using in my code for yahoo finance. I can navigate to it in the browser and it works like a charm. For the life of me I cannot understand why this isn't working.

var urlEncoded = "http://www.finance.yahoo.com/webservice/v1/symbols/" + textValue.toString() + "/quote?format=json";

Upvotes: 0

Views: 150

Answers (1)

Rainer Plumer
Rainer Plumer

Reputation: 3753

You could try jQuery, google and download it. It's a javascript framework that makes things allot simpler .

$.get( "http://yourur.com/file.php?parameter1=value1&parameter2=value2", function( data ) {
    //data now contains whatever it loaded from server
    console.log("Loaded from server :", data);
}, "json");

Upvotes: 2

Related Questions