0

In the below piece of code I am not getting the locale in the second alert

if `value==null`

I assign its locale value. but do not get it at the end.

function getLocale(id) {
    var locale="";
    var value = localStorage.getItem(id);
    if (value == null) {
        $.ajax({
            type: "POST",
            url: "myUrl",
            data: {"new" : id},
            success : function(data) {
                data = JSON.parse(data)
                var id = data[0]["id"];
                delete data[0]["id"];
                localStorage.setItem(id, JSON.stringify(data[0]));
                locale=JSON.stringify(data[0]);
                alert(locale);//corrects value
            }// end success
        });
    }else{
        locale= localStorage.getItem(id);
    }
    alert(locale+"locale");//not have the value
    return locale;
}
Netorica
  • 18,523
  • 17
  • 73
  • 108
Govind Singh
  • 15,282
  • 14
  • 72
  • 106

2 Answers2

1

Its not because of the scope. It is because of the asynchronous behaviour of ajax call. Because the function will not wait for the success event of ajax.

If you want to return, you should use async:false in ajax. But it is not a good method of coding.

Or you should restructure your code with the asynchronous ajax. Instead of returning the value, call a function in the ajax success with desired id.

Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
1

ajax request is an async process which means it has a different execution timing with your function returning a value.

the trick here is do not assume to have a return value in the scope of the function. do all the process in the success call back function

    success : function(data){
      //do everything what you want to do with the response here
    }
Netorica
  • 18,523
  • 17
  • 73
  • 108
  • i need this function diffrent times, so i need to return value – Govind Singh Apr 23 '14 at 08:47
  • you are doing it wrong if you push your self for a return value of an ajax request because ajax has a different timing(except if you will do `async:false` but it will lead you to more problems), what you can do is to call all the functions you need to process in the callback or else you will be leading yourself in a dirty way of solving your problem – Netorica Apr 23 '14 at 08:48