0

I want to make a js function that refreshes the CSRF token (that i stored in a div) and return the new value after it has been refreshed.

The problem is that i can not define the new token to my returning variable.

In this post i found out how to wait until the .load() function has finished. But how can i return the new token/value?

This is what i try to do.

function getCsrfToken() {

var csrfToken = null;
$("#csrf-token").load(location.href + " #csrf-token", function () {
    csrfToken = $("#csrf-token").text();
});
// csrfToken is undefined here
return csrfToken;

}

  • 2
    You can not return from an asynchronous method. It is like trying to eat a delivery pizza before it is at your house. – epascarello Jan 25 '18 at 14:19
  • `load()` makes an **asynchronous** ajax request – charlietfl Jan 25 '18 at 14:19
  • This post might help : https://stackoverflow.com/a/32163917/1636522. –  Jan 25 '18 at 14:27
  • @epascarello why do you mark this post as duplicate? Like i said, the second anonymous function fires when the .Load() function is finished (is it still a asynschonous request? i was assuming that it will change in a synchronous request like async: false). Thanks leaf that helped a lot, now i have learned that this is bad practice. – Silas de Rooy Jan 26 '18 at 08:09
  • Duplicate because questions like `asynchronousTask(function (result) { v = result; }); doSomethingWith(v);` have been posted many times before. Don't take it personal, contributors at Stackoverflow just care to keep this great and free website as clean as possible. Welcome aboard :-) –  Jan 26 '18 at 09:18
  • Why is it marked s dupe? Because it is. Load is asynchronous. When that function runs that return statement has already run. Both links above have tons of different solutions. Either you need to change your logic to use a callback or use the modern approach with promises. – epascarello Jan 26 '18 at 12:37

0 Answers0