function get_users () { let users; $.ajax({ url: "http://blog.good-electric.ru/config/users.php", method: "GET", complete: function(xhr, status) { console.log(status, xhr); } }).done(function (data) { users = data; }); return users; } 

complete returns status_code - error, please tell me where is the error?

  • please tell me where is the error? - Without the exact text of the error can not be said. Either on the server or not the client :) - Grundy

1 answer 1

Your get_users function get_users asynchronous, which means that the users variable in it with return will always be undefined .

The function can be made synchronous in several ways.

Promise constructor method:

 function get_users() { return new Promise((resolve, reject) => { $.ajax({ url: "http://blog.good-electric.ru/config/users.php", method: "GET", success: resolve, error: reject }) }) } get_users() .then(data => console.log('success', data)) .catch(err => console.log('err', err)) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

By callback method:

 function get_users(success, error) { $.ajax({ url: "http://blog.good-electric.ru/config/users.php", method: "GET", success: success, error: error }) } get_users(data => { consoe.log('success', data) }, err => { console.log('err', err) }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

  • but the question asks about the output of console.log: complete: function(xhr, status) { console.log(status, xhr); } complete: function(xhr, status) { console.log(status, xhr); } which displays status_code - error - Grundy
  • if the question was about the value of users , then it would be worth voting for closing as a duplicate: How to return a value from an event or from a callback function? Or at least wait for them to end - Grundy
  • the get_users function will not work by itself unless the issue is asynchronous. And the error may occur due to CORS - mix
  • get_users - works fine by itself. And judging by the fact that the status comes - most likely an error on the server, not cors, but nothing can be said without the error text, perhaps this is an attempt to bring an invalid json to the object dropped - Grundy
  • You can make a function synchronous in several ways - none of the above methods does NOT make a function synchronous - Grundy