How to return the response from a message in a variable? JQuery

edited: This is what I need:

sendpost = function(a,b,c){
    return jQuery.post('inc/operations.php', {a:b}, c, "json");
},

rotate = function(callback){
    //....
    alert(callback);
}

sendpost('operation', 'test', rotate)

old message: I use this function to return a message reply:

$.sendpost = function(){
    return jQuery.post('inc/operations.php', {'operation':'test'}, "json");
},

I want to do something like this:

at

$.another = function(){
  var sendpost = $.sendpost();
  alert(sendpost);
}

but I get: [object XMLHttpRequest]

if I print an object with:

jQuery.each(sendpost, function(i, val) {
  $(".displaydetails").append(i + " => " + val + "<br/>");
});

I get:

details  abort => function () { x && h.call(x); g("abort"); }
dispatchEvent => function dispatchEvent() { [native code] }
removeEventListener => function removeEventListener() { [native code] }
open => function open() { [native code] }
setRequestHeader => function setRequestHeader() { [native code] }
onreadystatechange => [xpconnect wrapped nsIDOMEventListener]
send => function send() { [native code] }
readyState => 4
status => 200
getResponseHeader => function getResponseHeader() { [native code] }
responseText => mdaaa from php

How to return only the answer in a variable?

+3
source share
1 answer

It's impossible.

AJAX calls are asynchronous, which means your code continues to run before the server sends a response.

When the statement is executed return, there is no response from the server yet.

You can make a synchronous AJAX call, but it will completely freeze the browser and should be avoided at all costs.

, , $.post. ( jQuery AJAX )

EDIT: :

$.sendpost = function(callback) {
    return jQuery.post('inc/operations.php', {'operation':'test'}, callback, "json");
};

$.another = function() { 
    $.sendpost(function(response) {
        alert(response);
    });
};
+4

Source: https://habr.com/ru/post/1742670/


All Articles