ThatGuyYouKnow
ThatGuyYouKnow

Reputation: 227

Use a function to set a variable with Javascript?

I am trying to use javascript and jquery to build an HTML table based on information returned from a database. I have the JSON and the database hit working properly, but I am unable to show the data on my page.

This is code to display the data

var temp;

var init = function() {
    $(_getMarketInfo()).appendTo(document.body);

    // Used for logging
    temp = $(_getMarketInfo());
    console.log(temp);
};

And then to get and process the data

function _getMarketInfo() {
    $.ajax({
        url:'scripts/db_getMarketInfo.cgi',
        dataType:'json',
        success:function(data, testStatus) {
            var html = '';
            html +='<div class="marketInfoHolder">';
            html +='<table class="tbl" border=1>';
            html +='    <tr><th>Market Information</th></tr>';
            html +='    <tr><td>Market</td></tr>';

            for (var i=0;i< data.marketInfo.length; i++){
                html += '<tr><td>' + data.marketInfo[i].market_name + '</td></tr>';
            }

            html +='</table>';
            html +='</div>';

            //used for logging
            console.log(html);

            return html;
        },
        error:function(data, textStatus) {
            alert('There was an error getting market information.');
        }
    });
 };

According to the console logs, the html variable does have proper html code for a table, but then when I look at temp variable, it is logged as []. It appears that, for some reason, the _getMarketInfo() isn't properly returning html to temp.

Upvotes: 0

Views: 1104

Answers (3)

draeton
draeton

Reputation: 685

I would use a custom event that is triggered on the success of the ajax call.

var init;

// bind a custom event to the document that is
// triggered in your ajax success callback
$(document).bind('init', function (html) {
    init = html;

    // Used for logging
    console.log(init);    
});

// run _getMarketInfo in a document ready handler
// because you are accessing the DOM
$(document).ready(function () {
    $(_getMarketInfo()).appendTo(document.body);    
});

// your ajax call function
function _getMarketInfo() {
    $.ajax({
        url:'scripts/db_getMarketInfo.cgi',
        dataType:'json',
        success:function(data, testStatus) {
            var html = '';
            html +='<div class="marketInfoHolder">';
            html +='<table class="tbl" border=1>';
            html +='    <tr><th>Market Information</th></tr>';
            html +='    <tr><td>Market</td></tr>';

            for (var i=0;i< data.marketInfo.length; i++){
                html += '<tr><td>' + data.marketInfo[i].market_name + '</td></tr>';
            }

            html +='</table>';
            html +='</div>';

            // trigger your custom event with
            // the html used as a custom parameter;
            // custom event parameters must be passed
            // in an array
            $(document).trigger('init', [html]);

            // return your html for appending
            return html;
        },
        error:function(data, textStatus) {
            alert('There was an error getting market information.');
        }
    });
 };

Upvotes: 0

Michiel Cornille
Michiel Cornille

Reputation: 2097

just move your appendTo logic inside the success:function(data, testStatus) { of your ajax call

Upvotes: 1

ullmark
ullmark

Reputation: 2479

You can't return that way from the success function since ajax is run async. Also if you wrap stuff in $() they will become an array since that's the way jQuery works.

var init = function() {
  $.ajax({
    url: 'scripts/db_getMarketInfo.cgi',
    dataType: 'json',
    success: marketsDownloaded,
    error: errorRecieved
  });
},

marketsDownloaded = function(data, status) {
  // build your html here and append it to body
},

errorRecieved = function(data, status) {
}

$(function() {
  init();
}

You could also put the code in somekind of namespacing to clean it up even more

Upvotes: 0

Related Questions