-1

Below is my javascript code.. I am declaring the variable 'allproductsAndPrice' outside the function.. But I am not able to access it after i initialize it.! Am i doing something wrong? when I try to alert it, It doesn't print anything.

var allproductsAndPrice = "";
$.getJSON("/Home/GetProducts",
    function (data, textStatus, jqXHR) {
        for (var i = 0; i < data.length; i++) {
            allproductsAndPrice = allproductsAndPrice + 
                "<option name='productName' id=" + data[i].productPrice + ">" + 
                data[i].Pname + "</option>";
        }
    }
);

alert(allproductsAndPrice);
krillgar
  • 12,596
  • 6
  • 50
  • 86
Uthaiah
  • 1,283
  • 13
  • 14

2 Answers2

1

What's wrong here is that the alert will be called before the getJSON's callback will be called. Which means that allProductsAndPrice is always an empty string in the alert.

The call to getJSON is asynchronous which means that it will trigger a "complete" event on the ajax request and then the callback will get executed. You could make the call to getJSON synchronous but that is kind of against the idea.

To get a better idea of what is happening right now is this:

  1. Initialize allproductsAndPrice to "" on the current scope.
  2. Create an Ajax request
  3. Alert with the content of allproductsAndPrice which is still ""
  4. Complete event is triggered
  5. Execute callback and affect something to allproductsAndPrice

What you should do instead is this:

    var allproductsAndPrice = "";
    $.getJSON("/Home/GetProducts",
      function (data, textStatus, jqXHR) {
          for (var i = 0; i < data.length; i++) {
              allproductsAndPrice = allproductsAndPrice + "<option name='productName' id=" + data[i].productPrice + ">" + data[i].Pname + "</option>";
          }

          // More code that should be executed
          alert(allproductsAndPrice);
    });
Loïc Faure-Lacroix
  • 13,220
  • 6
  • 67
  • 99
0

try this. This will work and help you in identifying if there is an error. And second thing var allproductsAndPrice will remain empty in alert because ajax request is async, javascript will not wait for ajax response.

var allproductsAndPrice = "";
try {
    $.getJSON("/Home/GetProducts", function(data) {
        for (var i = 0; i < data.length; i++) {
            allproductsAndPrice = allproductsAndPrice + "<option name='productName' id=" + data[i].productPrice + ">" + data[i].Pname + "</option>";
        }
    });
} catch (e) {
    alert(e.message);
}
alert(allproductsAndPrice);
Ankush Jain
  • 5,654
  • 4
  • 32
  • 57