Question

I am trying to retrieve stock information using YQL query in my ASP.NET project. I am using jquery to make json call to retrieve the data. The issue is when i click the 'GetData' button on my page, it just refreshes the page and no data gets displayed. If i run the project in debug mode in visual studio, it returns the stock information and displays on the page however by the end of the debug it clears the page. Here is the code:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="Scripts/jquery-1.11.0.min.js" type="text/javascript"></script>

        <script type="text/javascript">
            function getData() {
                var url = "http://query.yahooapis.com/v1/public/yql";
                var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('MSFT')");
                $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
            .done(function (data) {
                $("#result").text("Bid Price: " + data.query.results.quote.LastTradePriceOnly);
                alert(data.query.results.quote.LastTradePriceOnly);
            })
            .fail(function (jqxhr, textStatus, error) {
                var err = textStatus + ", " + error;
                $("#result").text('Request failed: ' + err);
            });
            }

        </script>
    </head>
    <body>

        <form id="form1" runat="server">    
            <div id='result'>No Price</div>
            <button type="submit" onClick="getData();">Get Data</button>         
        </form>
    </body>
    </html>

JsFiddle: http://jsfiddle.net/a3tuP/

Does anyone know why the data gets cleared even though the data gets returned in JSON call?

Thanks.

Was it helpful?

Solution

The form is submitted by your submit-action on the button Try re-factor to something like this and add .preventDefault()

HTML

 <form id="form1" runat="server">    
        <input type="text" id="symbol" />
        <div id='result'>No Price</div>
        <button type="submit">Get Data</button>
    </form>

JS

function getData(e) {
    //prevent sumbitting the form 
    e.preventDefault()
    var url = "http://query.yahooapis.com/v1/public/yql";
    var symbol = $("#symbol").val();
    var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('BGG')");

    $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
        .done(function (data) {
        $("#result").text("Bid Price: " + data.query.results.quote.LastTradePriceOnly);
    })
        .fail(function (jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
            $("#result").text('Request failed: ' + err);
    });
}

//bind the submit event
$(document).on("submit", "#form1" getData)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top