P
P
Partizanin2015-04-08 21:59:34
JavaScript
Partizanin, 2015-04-08 21:59:34

How to return json response to another function from a function with ajax request?

There is a function with an ajax request that returns Json, but I can’t return it, I can only work in the success field: !
How can I return a response from the server so that I can work with it in multiple functions?

function callServeToChangeExchange(exchange, operation) {

    var myData = {"operationCall": operation, "exchange": exchange};

    loader("show");

    $.ajax({
        type: "GET",
        url: "/ConventerServlet",
        data: {jsonData: JSON.stringify(myData)},
        dataType: "json",

        //if received a response from the server
        success: function (data) {
            document.getElementById("exchange1").value = data.exchange1;
            document.getElementById("exchange2").value = data.exchange2;
            document.getElementById("exchange3").value = data.exchange3;
            document.getElementById("exchange4").value = data.exchange4;
            count($("#inputValue").val());
            /*loader("hide")*/
        },

        error: function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus, errorThrown);
        },

        complete: function () {
            loader("hide")
        }

    });

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Petrov, 2015-04-08
@Partizanin

If I understand correctly, you need a promise object , which jQuery implements as a Deferred object .

function callServeToChangeExchange (exchange, operation) {
  var defer = $.Deferred();
...
  $.ajax({
...
  }).done(function (data) {
    // Вот так теперь рекомендуют вместо success
    defer.resolve(data);
  });
  return defer.promise();
}

callServeToChangeExchange().then(function (data) {
  // А вот и данные запроса
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question