Search code examples
javascriptjqueryajaxvar

Why global var type variable is not accessible outside $.each when using in $.post method?


I was going through a piece of code when I found that this variable is throwing an error.

function call(data) {
  $.each(data, function(index, value) {
    var ddlId = 'ddlCat' + data[index].docId;
    var html = '<tr id="supp_doc_row_' + data[index].docId + '" class="cls-delete-dynamic_edit">';
    var html2 = '';
    var countDocOfsameCategory = parseInt(data[index].countt) - 1;
  })

  $.post('/someController/SomeAction/', {
    requestType: 'GETDOC'
  }, function(data1) {
    $("#" + ddlId).empty();
    $("#" + ddlId).append($('<option value= "Select"> Select Type</option>'));
  })
}

Now the problem is that i was treating this ddlId variable as global. So I had used this inside post method. But I got this in my console.

Uncaught ReferenceError: ddlId is not defined

at Object.success (<anonymous>:1110:38)
at u (jquery-3.3.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.3.1.min.js:2)
at k (jquery-3.3.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.3.1.min.js:2)

When I debugged it in console then I found that in $.each call it had value but in $.post it has gone.

Can any one tell me how this global variable lost its state?


Solution

  • var makes the variable global for the specific scope. A var defined inside a function can be accessed inside the function anywhere but won't be accessible outside because it is not its scope. Define the var in the global scope outside the function and all your functions will have access to it.