Web API With AJAX: Understand Synchronous and Asynchronous Call in jQuery ajax Method

This article is intended to provide a practical understanding of synchronous and asynchronous calls.

I hope you know what you are reading, Ha..Ha..Yes this is the article series on the "Web API with AJAX". If you are a regular reader of this series then please skip the following links and proceed to the next part. Oh, is this the first time you are here? Enjoy the following previous articles in this series:

This article is intended to provide a practical understanding of synchronous and asynchronous calls. I can guarantee (yes, almost) that all of you know that ajax() executes asynchronously and it's cool for modern web application. How many of you have executed an ajax() function synchronously? Very few, I guess. Ok, you know that it is possible to execute synchronously but you have not tried it (actually neither have I tried it until I wrote this article). Anyway, let's get to the technical explanation. At first we will call an ajax() method asynchronously and we will see how it works practically.

Implement ajax() method in client part

This implementation is very well known, nothing special is here. We have only defined or ajax() method within firstfunction() and it will call one API that will act as a heavy process (we will implement it shortly). At the end of the ajax() function we are calling another JavaScript function, so when it is called after the ajax() function, it should execute after the finish of the ajax() function if it is an asynchronous process but since it is an asynchronous operation the function will be called before the finish of the ajax() function and this is what we expect from the ajax() function in jQuery. Here is the code implementation of this scenario. 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestWEB_API.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>
    <script>
        $(document).ready(function () {
            //Calling to LongProcess()
            LongProcess();
            function firstfunction() {
                console.log('I should execute after LongProcess function');
            }
            function LongProcess() {
                $.ajax({
                    url: 'http://localhost:11129/api/values',
                    type: 'GET',
                    dataType: 'json',
                    success: function (data, textStatus, xhr) {
                        console.log(data);
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        console.log('a' + textStatus);
                    }
                });
                //Call to first function after ajax() function defination
                firstfunction();
            }
        });
    </script>
</head>
<body>
</body>
</html>

Oh, I nearly missed one point. We did not define any property for synchronous and asynchronous calls. By default an ajax() function is executed asynchronously. Cool. Now concentrate on the Web API implementation.

Here is sample code for the Web API. We have just defined the Value controller (oh, not defined it; it was there with the template, but modified) and within that the Get() action is performed as a heavy wait process.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TestWEB_API.Models; 

namespace TestWEB_API.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values
        public string Get()
        {
            System.Threading.Thread.Sleep(5000);
            return "Oh ! at last long process finish";
        }
    }
}

 

Here is the output. The function that we are calling after the ajax() method is executing first. In other words, the ajax() method is not being blocked from executing of it's next line of code.



Execute ajax() method synchronously

This is the main purpose of this article, to see how an ajax() method executes synchronously. Have a look at the following code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestWEB_API.WebForm1" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>
    <script>
        $(document).ready(function () {
            //Calling to LongProcess()
            LongProcess();
            function firstfunction() {
                console.log('I should execute after LongProcess function');
           }
            function LongProcess() {
                $.ajax({
                    url: 'http://localhost:11129/api/values',
                    type: 'GET',
                    dataType: 'json',
                    async:false,
                    success: function (data, textStatus, xhr) {
                        console.log(data);
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        console.log('a' + textStatus);
                    }
                });
                //Call to first function after ajax() function defination
                firstfunction();
            }
        });
    </script>
</head>
<body>
</body>
</html>

 

It is very similar to the example above except we have added one extra property with the definition of the ajax() method. The property is "async:false", that's enough.

Here is the old API implementation.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TestWEB_API.Models; 

namespace TestWEB_API.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values
        public string Get()
        {
            System.Threading.Thread.Sleep(5000);
            return "Oh ! at last long process finish";
        }
    }
}

 

Now we see that the ajax() method is finishing first and then the JavaScript function is being called. Cool, we are finished with our experiment.



Conclusion

I never seen such a crazy developer who calls ajax() synchronously. Of course there might be a scenario where it is relevant. If you have seen that please leave a comment.