YeahStu
YeahStu

Reputation: 4052

Successful jQuery Ajax call cannot be processed asynchronously

I have the below javascript code and I cannot get it to return to the .done handler unless I set async: false on the ajax call. If I don't include the async: false parameter on my ajax call, nothing happens on the client after the service returns.

Here is my javascript code:

$(function () {
    $('#testButton').click(function () {
        TestConnection();
    });
});

function TestConnection() {
    $.ajax({
        url: 'http://localhost:52180/api/Accounts/Test',
        type: 'POST',
        async: false
    }).done(function (data) {
        alert('Success');
    }).fail(function (jqXHR, textStatus, err) {
        alert("There was an error communicating with the Mojo-Store server.");
    });
}

My Html is very simple. As you can see, I'm referencing jQuery 3.1.1:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <script src="jquery-3.1.1.min.js"></script>
    <script src="ServerCommunication.js"></script>
</head>
<body>
                <button id="testButton">
</body>
</html>

In my Web API project I have a simple method:

public class AccountsController : ApiController
    {
        public AccountsController ()
        {
        }

        public bool Test()
        {
            return true;
        }
    }

I can see that the server is called but I never get the 'Success' message unless I have the async: false parameter. I'd like to remove that. What do I have to do to fix this issue?

Upvotes: 0

Views: 631

Answers (1)

Pie
Pie

Reputation: 351

You'll have to work with a callback function if you want to use the success and error of an ajax call. Ajax is asynchronous by default and will immediatly call the return function after it loads. When you add async:false, then the whole ajax call is no longer asynchronous and will be able to call the success and error.

Try something like this to keep working asycnhronous:

$(function () {
    $('#testButton').click(function () {
        TestConnection(Callback);
    });
});

function TestConnection(callbackfn) {
    $.ajax({
        url: 'http://localhost:52180/api/Accounts/Test',
        type: 'POST',
        success: function (data) {
            callbackfn("Success");
        },
        error: function (jqXHR, textStatus, err) {
            callbackfn("There was an error communicating with the Mojo-Store server.");
    });
}

function Callback(data) {
    alert(data);
 }

Upvotes: 1

Related Questions