1

I am making an ajax call and returning an array of json data. I am then attempting to do an each on the object and create some HTML.

success: function (data) {
   var abc = null;
   var obj = $.parseJSON(data);
   $.each(obj, function(key, value) {
   abc += '<option value="' + key + '">' + value + '</option>';
   }); 
}

when I place the variable abc in the console, within the .each function, I can see the output. However when i try to access the variable abc from outside the .each function, I get an error message Uncaught ReferenceError: abc is not defined

Matthew Colley
  • 10,816
  • 9
  • 43
  • 63
  • How you access abc from outside ? – Adil Shaikh May 10 '13 at 18:20
  • Outside where? outside the success callback? Also for string append, you should define it as `var abc = ""` instead of null. Defining null would return a end result with null in the beginning of the string. – Selvakumar Arumugam May 10 '13 at 18:20
  • you need to define abc as global variable, for now abc only exists inside of the success function. If you want to use the data outside the call you can have a look at this question http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Johnny000 May 10 '13 at 18:20

1 Answers1

1

Uncaught ReferenceError: abc is not defined - as the error says the variable abc is not accessible from where it is being accessed.

I think you are accessing abc outside success callback, but the scope of abc is inside callback as it is defined inside the callback. You can move the var declaration outside if you are going to access the variable outside the callback.

Also you should define it as var abc = "" instead of null. Defining null would return an end result string with null in the beginning.

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134