Calling Web API using jQuery AJAX

Calling Web API using jQuery AJAX

Calling Web API using jQuery AJAX-Lets you know How to use Web API with JQuery AJAX. Moreover, one of the best available javascript design and pattern based on object oriented two most famous concept Encapsulation and Polymorphism .

Before proceed further make sure you might visit following articles.

Module Pattern

REST full Web Api's

First you need to add Reference file for JQuery.
To download jQuery file click here.

We will create two layers here.

1st for jQuery Ajax Factory.

2nd for Web Services which will consume web api's.

At the end, We will invoke these web services, which will call web api's from Web form (View)

1). Generic JQuery Ajax Factory

var AjaxFactory = (function () { // Private Area var globalurl = "http://localhost:58708/Student/"; var ApiGet = function (u) { return $.ajax({ url: globalurl + u, method: "GET", dataType: "json", contentType: "application/json; charset=utf-8" }).fail(function (x, s, et) { console.dir(x); console.log(s); }); }; var ApiPost = function (u, d) { return $.ajax({ url: globalurl + u, method: "POST", data: JSON.stringify(d), dataType: "json", contentType: "application/json; charset=utf-8" }).fail(function (x, s, et) { console.dir(x); console.log(s); }); }; // Public Area return { ApiGet: function (url) { return ApiGet(url); }, ApiPost: function (url, data) { return ApiPost(url, data); }, } })();

globalurl : Set URL for your web api.

Public Method: AjaxFactory.ApiGet(url) Method is used to make HTTP GET Request. Here argument {url} is web api Method Name, which can be futher more extended like
{MethodName?id=12&name=swclass}.

Public Method: AjaxFactory.ApiPost(url,data) Method is used to make HTTP POST Request. Here first argument is web api Method Name. and second argument is {data}, which should be in the form of JSON like
{ "StudentId": "11", "StudentName": "New Student", "StudentClass": "8th", "StudentRollNo": "1" }

2nd Student Service

Here we creted two methods one for retrieve entire students data i.e
StudentService.GetStudents() and another to add new student i.e. StudentService.AddNew().

var StudentService = (function () { var GetAllStudents = function () { AjaxFactory.ApiGet("GetAllStudents").then(function (d) { if (d.StatusCode == 1) { BindStudents(d.ApiResponseData); } }); }; var BindStudents = function (s) {
            var d = '<table class="table"><tr><th>Student Id</th><th>Roll No.</th><th>Class</th><th>Name</th></tr>';
            for (var i = 0; i < s.length; i++) {
                d += '<tr>';
                d += '<td>' + s[i].StudentId + '</td>';
                d += '<td>' + s[i].StudentRollNo + '</td>';
                d += '<td>' + s[i].StudentClass + '</td>';
                d += '<td>' + s[i].StudentName + '</td>';
                d += '</tr>';
            }
            d += '</table>';
            $('#students').html(d);
        }; var AddNewStudents = function () { var p = { "StudentId": "11", "StudentName": "New Student", "StudentClass": "8th", "StudentRollNo": "1" }; AjaxFactory.ApiPost("AddNewStudent", p).then(function (d) { if (d.StatusCode == 1) { BindStudents(d.ApiResponseData); } }); }; return { GetStudents: function () { return GetAllStudents(); }, AddNew: function () { return AddNewStudents(); }, } })();

Now Finally we will call StudentService methods, Inside jQuery document ready method.

$(function() { console.log('Document is Ready..'); //StudentService.GetStudents(); StudentService.AddNew(); });

Which will fill div having id students.

<div class="row">
    <div class="col-md-12">
        <div id="students">
        </div>
    </div>
</div>

Follow my previous article MVC Web Api

Goto Views under {Solution Explorer}

Choose {Home}

Open file index.cshtml

Copy (Ctrl+C) and Replace (Ctrl+V) final code.

Press F5 or Alt+F5

@{ ViewBag.Title = "JQuery Using Web Api 2 With MVC"; } <div class="row">
    <div class="col-md-12">
        <div id="students">
        </div>
    </div>
</div> @section scripts{ <script> // Ajax Core Factory var AjaxFactory = (function () { var globalurl = "http://localhost:58708/Student/"; var ApiGet = function (u) { return $.ajax({ url: globalurl + u, method: "GET", dataType: "json", contentType: "application/json; charset=utf-8" }).fail(function (x, s, et) { console.dir(x); console.log(s); }); }; var ApiPost = function (u, d) { return $.ajax({ url: globalurl + u, method: "POST", data: JSON.stringify(d), dataType: "json", contentType: "application/json; charset=utf-8" }).fail(function (x, s, et) { console.dir(x); console.log(s); }); }; return { ApiGet: function (url) { return ApiGet(url); }, ApiPost: function (url, data) { return ApiPost(url, data); }, } })(); // Student Service var StudentService = (function () { var GetAllStudents = function () { AjaxFactory.ApiGet("GetAllStudents").then(function (d) { if (d.StatusCode == 1) { BindStudents(d.ApiResponseData); } }); }; var BindStudents = function (s) {
            var d = '<table class="table"><tr><th>Student Id</th><th>Roll No.</th><th>Class</th><th>Name</th></tr>';
            for (var i = 0; i < s.length; i++) {
                d += '<tr>';
                d += '<td>' + s[i].StudentId + '</td>';
                d += '<td>' + s[i].StudentRollNo + '</td>';
                d += '<td>' + s[i].StudentClass + '</td>';
                d += '<td>' + s[i].StudentName + '</td>';
                d += '</tr>';
            }
            d += '</table>';
            $('#students').html(d);
        }; var AddNewStudents = function () { var p = { "StudentId": "11", "StudentName": "New Student", "StudentClass": "8th", "StudentRollNo": "1" }; AjaxFactory.ApiPost("AddNewStudent", p).then(function (d) { if (d.StatusCode == 1) { BindStudents(d.ApiResponseData); } }); }; return { GetStudents: function () { return GetAllStudents(); }, AddNew: function () { return AddNewStudents(); }, } })(); // Form Loading ... $(function () { console.log('Document is Ready..'); //StudentService.GetStudents(); StudentService.AddNew(); }); </script> }

Calling Web API using jQuery AJAX- Hope you will learn a best javascript pattern to design a good javascript program not even for ajax web apis request, you can achieve more than it. If you have any query of suggestion or any question in your mind, Please let me know. Write your comments.

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories