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

function ajax_test(str1){ 
  var url = "None" 
    cache: false, 
    url: 'http://....' + str1, 
    success: function(data, status, xhr){ 
    error: function (xhr, status, e) {  
    async: true, 
    dataType: 'json' 
  return url 

How can I set the global variable url to be the returned success ajax data?



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){  
     //... your options
     success: function(data, status, xhr){  

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){
        type: "POST",  
        url: "readString.php",  
        data: { 'fn': filename },      
        success: function(response){

PHP code (readString.php):


     $fn  = $_POST['fn'];

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

     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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.