function ChatServerQuery(data_json) {
var result = null;
$.ajax({
url: 'chat/backend/',
type: 'POST',
data: data_json,
success: function(json) {
result = json
}
})
return result
}
My function that executes a request to the server. The problem is that I can not return received from the server text. I do not know how to take from an anonymous function (event success) to ChatServerQuery (where you can easily get it back).
Answer
You'd better change your approach to reflect an asynchronous nature of AJAX request.
Using callback function
function ChatServerQuery(data, callback) {
$.ajax({
url: 'chat/backend/',
type: 'POST',
data: data,
success: callback
});
}
Then you would use it:
ChatServerQuery(dataObject, function(data) {
// work with your data came from server
});
Using promise object
$.fn.ajax
returns object implementing Promise iterface, so you can use it like this:
function ChatServerQuery(data) {
return $.ajax({
url: 'chat/backend/',
type: 'POST',
data: data
});
}
ChatServerQuery(dataObject).done(function(data) {
// work with your data came from server
});
This option offers you more flexibility.
No comments:
Post a Comment