Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change a global variable in the wrapper JavaScript function after an ajax call? [duplicate]

function ajax_test(str1){    var url = "None"    jq.ajax({     type:'post',      cache: false,      url: 'http://....' + str1,      success: function(data, status, xhr){        url=data;      },      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?

like image 565
sammiwei Avatar asked Aug 11 '12 21:08

sammiwei


People also ask

How do you trigger a change event after ajax call?

One way to trigger an event is to use the jquery trigger function. Show activity on this post. function changeDate(){ $. ajax({ url, data: data, type: "POST", dataType: "json", success: function(cbdata) { update_table(cbdata); } }); } $('#selector').

What is global ajax?

Category: Global Ajax Event HandlersThese methods register handlers to be called when certain events, such as initialization or completion, take place for any Ajax request on the page. The global events are fired on each Ajax request if the global property in jQuery. ajaxSetup() is true , which it is by default.


1 Answers

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 }); 
like image 162
Peter Olson Avatar answered Sep 22 '22 09:09

Peter Olson