0

I am making an Ajax call in a another function function checkUrl(url){...}. When this function is called and Ajax request has been sent, and a response is got. I have declared a variable var str; inside this function checkUrl(url){...}. function, which is not in the scope of the Ajax function, so it means that variable str is global to the Ajax function. What I need is, when I get the response I want to assign that response to that global variable. But due to some reasons the variable is not getting to be initialized and its return statement is returning undefined value. When I initially assign an empty string or null value like var str = null; or var str = " "; then the function function checkUrl(url){...}. returns that value which has been initialized initially. I don't know why its not getting initialized during run time when I get the response.

My Code

function checkUrl(url){

   var str;
   $.ajax({
      method:"GET",
      url:"http://www.bitbaysolutions.com/connections.php?fbPostUrl=true",
      data:{
       url:url
      },
      success:function(r){
       console.log(r);
         switch(r){
          case "not_using_ext":{
           console.log("Script2 Says After Response : User is not using the extension ! ");
           str = "not_using_ext";
           break;
          }
          case "using_ext":{
            console.log("Script2 Says After Response : User is using the extension !");
                 str = "using_ext";
               break;
          }
         }
      }
   });
   alert("Value of str is :  " + str);
   return str;
   
}
Nadeem
  • 145
  • 1
  • 13
  • 1
    The AJAX call is asynchronous, which means that `str` is not set when you return it. See the duplicate question for the pattern you need to use to fix this issue – Rory McCrossan Sep 29 '17 at 06:55
  • @RoryMcCrossan they have provided the solution for pure javascript, how would I apply that for jquery ajax. They have used this ! `function ajax(url) { var str; return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.onload = function() { str = this.responseText; resolve(str); }; xhr.onerror = reject; xhr.open('GET', url); xhr.send(); }); } ajax("http://www.bitbaysolutions.com/") .then(function(result) { console.log(result); }) .catch(function() { // An error occurred }); ` – Nadeem Sep 29 '17 at 10:26
  • This answer in the question is using jQuery https://stackoverflow.com/a/21862907/519413 – Rory McCrossan Sep 29 '17 at 10:28

0 Answers0