jquery ajax call success, how do I change a global variable in the wrapper javascript function?

In Javascript, it is impossible for a function to return an asynchronous result. The function will usually return before the AJAX request is even made.

You can always force your request to be syncronous with async: false, but that's usually not a good idea because it will cause the browser to lock up while it waits for the results.

The standard way to get around this is by using a callback function.

function ajax_test(str1, callback){  
   jq.ajax({ 
     //... your options
     success: function(data, status, xhr){  
       callback(data);
     }
   });  
}  

and then you can call it like this:

ajax_test("str", function(url) {
  //do something with url
});

Here is my example code for retrieving data from php, and then pass the value to a javascript global variable within ajax success function. It works for me!

var retVal = null; 

function ajaxCallBack(retString){
    retVal = retString;
}

function readString(filename){
    $.ajax({  
        type: "POST",  
        url: "readString.php",  
        data: { 'fn': filename },      
        success: function(response){
            ajaxCallBack(response);
        }
    }); 
}

PHP code (readString.php):

<?php

     $fn  = $_POST['fn'];

     $file = fopen("path/".$fn.".record","r");
     $string = fread($file,filesize("path/".$fn.".record"));
     fclose($file); 

     echo $string;  
?>

However, as $.ajax() sent requests asynchronously, which means it may return before the success callback runs, you should not rely on it runs sequentially and return the value by itself. Therefore, here we assign php response value to global value in callback function.