Return The Response From An Asynchronous Call Ajax jQuery.

Sometimes we need to send a request to the server via an asynchronous call, the advantage of this is that we are not doing a full page refesh and wasting bandwidth for something that could be as simple as returning a thank you message.

There are many ways of doing this such as using XHR(XMLHttpRequest) but for this example I will be using jQuery and Ajax, which will send a request to a MVC controller and return the results.


To setup this example, we will create a javascript file that contains the code for sending and returning the response from an asynchronous call.

The code for the javascript file is below:

jQuery code

You now no longer need to add the $(document).ready, you can just use $(function()

$(document).ready(function () {
    $("#param").on("change", function (e) {
        e.preventDefault();
        $("#ajaxFindDetails").hide();
        $("#ajaxFindDetails").html("");
        jQuery.ajax({
            url: "/AsyncExample/Result",
            type: "POST",
            data: { 'param': $("#param").val() },

            success: function (result) {
                if (result.Confirm) {
                    $("#ajaxFindDetails").append(result.message).show();
                } else {
                    $("#ajaxFindDetails").append(result.message).show();
                }
            },
            error: function () {
                $("#ajaxFindDetails").html("Failed to find details");
            }
        });
    });
});

AjaxFindDetails is the ID of our div which will display the results of the async call to the MVC controller, if any results are found, they will be displayed here. If no results a found, then a message informing the user no results are found will display.

The code for the controller can be seen below:

Controller
using System;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Web.Model.TestSearchData;

namespace Web.UI.Controllers
{
    public class AsyncExampleController : Controller
    {
        // GET: AsyncExample
        public ActionResult Index()
        {
            return View("~/Views/AsyncExample/AsyncExample.cshtml");
        }

        [HttpPost]
        public ActionResult Result(string param)
        {
            //Before starting, we would check that param is not null!!
            var result = TestSearchData.DogList().Where(x=> string.Equals(x.PetTypeId, param, StringComparison.CurrentCultureIgnoreCase)).ToList();

            StringBuilder sb = new StringBuilder();
            
            if (result.Any())
            {
                sb.Append($"<h2 class=\"text-success\">Found {result.Count} results for {param}</h2>");
                sb.Append("<ol>");
                foreach (var pet in result)
                {
                    sb.Append($"<li>{pet.PetType}</li>");
                }

                sb.Append("</ol>");
            }
            else
            {
                sb.Append($"<h2 class=\"text-danger\">Found {result.Count} results for {param}</h2>");
            }

            string returnValue = sb.ToString();

            if (Request.IsAjaxRequest())
            {
                return Json(new { Confirm = true, message = $"{returnValue}" }, JsonRequestBehavior.AllowGet);
            }

            //Ignore this part as only doing async example
            return View("~/Views/AsyncExample/AsyncExample.cshtml");
        }
    }
}

The view contains a simple form with a textbox, once you enter either 'dog', 'cat' or 'fish' it will do an asynchronous call using jQuery and Ajax to the controller and do a search for the keyword. If a match is found, the results are displayed in the div else a message is shown that no results are found.

The rest of the code for this example can be found below.

Test data


The test data is a simple list that just returns a list of dogs, cats and fish.

Test Data
using System.Collections.Generic;
using Web.Model.TypesOfPets;

namespace Web.Model.TestSearchData
{
    public static class TestSearchData
    {
        public static IEnumerable<TypeOfPetsViewModel> DogList()
        {
            List<TypeOfPetsViewModel> typesOfPet = new List<TypeOfPetsViewModel>
            {
                new TypeOfPetsViewModel("dog", "German Shepherd"),
                new TypeOfPetsViewModel("dog", "Husky"),
                new TypeOfPetsViewModel("cat", "Russian Blue"),
                new TypeOfPetsViewModel("fish", "Goldfish")
            };
            return typesOfPet;
        }
    }
}

View Model

The view model is a simple class that just has properties for the test data to hold the dog data.

View Model
namespace Web.Model.TypesOfPets
{
    public class TypeOfPetsViewModel
    {
        public TypeOfPetsViewModel(string petTypeId, string petType)
        {
            PetTypeId   = petTypeId;
            PetType     = petType;
        }

        public string PetTypeId     { get; }
        public string PetType       { get; }
    }
}

View

The view contains a simple form with one textbox, enter 'dog','cat' or 'fish' and this will fire the asynchronous call to the jQuery code that has a on change function that waits for the textbox value to change.

View Code
@{
    ViewBag.Title = "Async Example";
}

<h2>Async Example</h2>


<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h1>Search Using jQuery Ajax Async</h1>
            <form name="frmAsync" id="frmAsync">
                <div class="form-group">
                    <input class="form-control" type="text" name="param" id="param" placeholder="Enter keyword 'dog' or 'cat' or 'fish'" />
                </div>
            </form>
            <div id="ajaxFindDetails"></div>
        </div>
    </div>
</div>

@section AsyncExample
{

    <script src="~/Scripts/CustomScripts/asyncExample.js"></script>
}

I hope you found this example helpful, if yes please leave a comment below.

Blog Form

 Please complete the required fields (*required)

 *
*