niczak
niczak

Reputation: 3917

Passing result from .getJSON() to another function results in undefined

Good day everyone,

I am pulling back some data from a database (via a PHP script) using jQuery's .getJSON() method. This is all well and good, the data comes back just fine and as expected. The problem occurs when I try to pass the data to a secondary function, no matter how I try to access the values of that data they come back as undefined. I have a feeling I am overlooking something very simple but after a lot of trial and error I come to SO asking for an extra set of eyes.

Here is a simple example of the JavaScript code.

  function fnCheck_Vis(Row, sField, sMode)
  {
    sField = sField+"_vis";
    sTest = Row.sField.val();
    alert(sTest); // Comes back as undefined.
  }

  $(document).ready(function()
  {
    $("#btnSearch").click(function()
    {
      $("#divResults").empty();
      var ssearch = $("#ssearch").val();
      var i = 0;
      $.getJSON("get_results.php?keywords=" + ssearch,
      function(Data)
      {
        var iRec = 0;
        $.each(Data, function(i, Row)
        {
          fnCheck_Vis(Row, "slinkpic1", "Int");
          var content = Row.slast;
          $("#divResults").append(content);
          iRec++;
        });
        alert(iRec + " records retrieved using AJAX.");            
      });
    });
  });

The first piece of the fnCheck_Vis() function works fine and "_vis" is appended to the field name, this is proper behavior. No matter how I try to access that member in the dataset (Row) I can not get a value back.

I really appreciate any insight that can be given on this issue.

Thanks,

Nicholas

Upvotes: 1

Views: 677

Answers (1)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262929

It looks like you want to access the property of Row whose name is stored in sField, not its actual sField property. Try:

function fnCheck_Vis(Row, sField, sMode)
{
    sField = sField + "_vis";
    var sTest = Row[sField];
    alert(sTest);
}

Upvotes: 3

Related Questions