Showing posts with label JQuery AJAX. Show all posts
Showing posts with label JQuery AJAX. Show all posts

Wednesday, 8 October 2014

Implementing & Consuming ASP.NET WEB API from JQuery (MVC 4)

CodeProjectIn this post we will see how to create a our own WEB API service and will consume it in client using JQuery.This is the UI i am planning to create, which in-turn talk to a ASP.NET WEB API Service for rendering data. We need to create a API Service and an Application consuming it.Lets do i
 
In this post we will see how to create a our own WEB API service and will consume it in client using JQuery.
This is the UI i am planning to create, which in-turn talk to a ASP.NET WEB API Service for rendering data. We need to create a API Service and an Application consuming it.

Dodaj napis


Lets do it step by step.

Step 1: Create a solution and add 2 MVC 4 projects , one with WEB API template and another with INTERNET Application template.



Step 2: Lets create our custom WEB API Service. Go to API_SVC project and under Controllers folder you can see ValuesController.cs. This is the default WEB API service fie added, either you can modify, or you can add a new API Controller, using Add option.



 Step 3:I created a Service file with name "EmployeeAPI". EmployeeAPIConstroller.cs
namespace API_SVC.Controllers
{
    public class EmployeeAPIController : ApiController
    {
        private List<employee> EmpList = new List<employee>();
        public EmployeeAPIController()
        {
            EmpList.Add(new Employee(1, "Employee1", "Employee Department1", 9999888877));
            EmpList.Add(new Employee(2, "Employee2", "Employee Department2", 7777888899));
            EmpList.Add(new Employee(3, "Employee3", "Employee Department3", 9999777788));
        }
        // GET api/EmployeeAPI
        public IEnumerable<Employee> GetEmployees()
        {             
             return EmpList;   
        }

        // GET api/EmployeeAPI/5
        public Employee GetEmployee(int id)
        {
            return EmpList.Find(e => e.ID == id);
            
        }

        // POST api/EmployeeAPI
        public IEnumerable<Employee> Post(Employee value)
        {
            EmpList.Add(value);

            return EmpList;
        }

        // PUT api/EmployeeAPI/5
        public void Put(int id, string value)
        {

        }

        // DELETE api/EmployeeAPI/5
        public IEnumerable<Employee> Delete(int id)
        {
            EmpList.Remove(EmpList.Find(E => E.ID == id));
            return EmpList;
        }
    }
}</employee></employee>

Step 4:I ensure that it is hosted on IIS and can be accessed through URL mentioned on each of the service methods. for example lets check GetEmployee() method using Fiddler.
Action:


Result:


Now that we confirm that we are done with creation of simple WEB API HTTP Service.

Step 5:  Move to the second application i.e., API_APP , the MVC 4 internet application, and open Index.cshtml under Home. To demonstrate the simplicity of ASP.NET WEB API Service, i will call them using nothing but JQuery i.e., Client side code.  Index.cshtml Code View:
@{
    ViewBag.Title = "Home Page";
}
@section featured {
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h1>@ViewBag.Title.</h1>
                <h2>@ViewBag.Message</h2>
            </hgroup>
            <div>
                <table><tr>
                        <td><button onclick="GetAllEmployees();return false;">Get All Employees</button></td>
                        <td>Enter Employee Id: <input type="text" id="txtEmpid" style="width:50PX"/></td>
                        <td><button onclick="GetEmployee();return false;">Get Employee</button></td>
                    <td>
                        <table>
                            <tr><td>EmpId:</td><td><input type="text" id="txtaddEmpid" /></td></tr>
                            <tr>  <td>Emp Name:</td><td><input type="text" id="txtaddEmpName" /></td></tr>
                            <tr> <td>Emp Department:</td><td><input type="text" id="txtaddEmpDep" /></td></tr>
                            <tr><td>Mobile no:</td><td><input type="text" id="txtaddEmpMob" /></td></tr>
                        </table>
                    </td>
                        <td><button onclick="AddEmployee();return false;">Add Employee</button></td>
                    <td>Delete Employee <input type="text" id="txtdelEmpId" style="width:50PX"/></td>
                        <td><button onclick="DeleteEmployee(); return false;">Delete Employee</button></td>
                       </tr></table>
                
            </div>
        </div>
    </section>
}
<h3>Oputput of action done through WEB API:</h3>
<ol class="round">
    <li>
        <div id="divResult"></div>

    </li>
</ol>

Index.cshtml UI view


Step 6: Lets see how we can associate each button to an action of API Service. First look at "Get All Employees" button and its onclick event in above code.Its is calling "GetAllEmployees()" , a script function in-turn calling WEB API Service using JQuery.
function GetAllEmployees() {
        jQuery.support.cors = true;
        $.ajax({
            url: 'http://localhost:8080/API_SVC/api/EmployeeAPI',
            type: 'GET',
            dataType: 'json',            
            success: function (data) {                
                WriteResponse(data);
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });        
    }
Spare sometime looking at above code snippet. See the URL part of Ajax Get request, that is all we need to consume the WEB API Service we created earlier. Make sure you give all the parameters properly so that it invoke right methods.
Step 7:  WriteResponse() and ShowEmployee() are the 2 methods i created to display the JSON result in a proper way. Below is the JQuery part associating each button to a method of WEB API Service.
<script type="text/javascript">
    function GetAllEmployees() {
        jQuery.support.cors = true;
        $.ajax({
            url: 'http://localhost:8080/API_SVC/api/EmployeeAPI',
            type: 'GET',
            dataType: 'json',            
            success: function (data) {                
                WriteResponse(data);
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });        
    }

    function AddEmployee() {
        jQuery.support.cors = true;
        var employee = {
            ID: $('#txtaddEmpid').val(),
            EmpName: $('#txtaddEmpName').val(),
            EmpDepartment: $('#txtaddEmpDep').val(),
            EmpMobile: $('#txtaddEmpMob').val()
        };       
        
        $.ajax({
            url: 'http://localhost:8080/API_SVC/api/EmployeeAPI',
            type: 'POST',
            data:JSON.stringify(employee),            
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                WriteResponse(data);
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });
    }

    function DeleteEmployee() {
        jQuery.support.cors = true;
        var id = $('#txtdelEmpId').val()       
        
        $.ajax({
            url: 'http://localhost:8080/API_SVC/api/EmployeeAPI/'+id,
            type: 'DELETE',            
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                WriteResponse(data);
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });
    }

    function WriteResponse(employees) {        
        var strResult = "<table><th>EmpID</th><th>Emp Name</th><th>Emp Department</th><th>Mobile No</th>";        
        $.each(employees, function (index, employee) {                        
            strResult += "<tr><td>" + employee.ID + "</td><td> " + employee.EmpName + "</td><td>" + employee.EmpDepartment + "</td><td>" + employee.EmpMobile + "</td></tr>";
        });
        strResult += "</table>";
        $("#divResult").html(strResult);
    }

    function ShowEmployee(employee) {
        if (employee != null) {
            var strResult = "<table><th>EmpID</th><th>Emp Name</th><th>Emp Department</th><th>Mobile No</th>";
            strResult += "<tr><td>" + employee.ID + "</td><td> " + employee.EmpName + "</td><td>" + employee.EmpDepartment + "</td><td>" + employee.EmpMobile + "</td></tr>";
            strResult += "</table>";
            $("#divResult").html(strResult);
        }
        else {
            $("#divResult").html("No Results To Display");
        }
    }
   
    function GetEmployee() {
        jQuery.support.cors = true;
        var id = $('#txtEmpid').val();        
        $.ajax({
            url: 'http://localhost:8080/API_SVC/api/EmployeeAPI/'+id,
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                ShowEmployee(data);
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });
    }
</script>
Step 8: What else we left with except verifying the output.
Action 1:

Action 2:

Action 3:

Action 4:

Step 9: Apart from fact that it is simple to configure and create, we need to consider that its a RESTful service which is light weight and will have  incredible performance.
Look at the below snapshot of HttpWatch Log for Action #1, which was completed in 50 milli seconds. I accept both applications are on same machine and solution, but the communication never happened through dlls. The execution happened via IIS just like typical service call. Even if you add the Network lag, we should say it is a good performance.

Monday, 11 August 2014

$.ajax, $.get, $.post, $.getScript, $.getJson differences in jquery

GET vs POST
·         A GET request is used to get data from the server.
·         A POST request is used for modifying data on the server.
When to use GET
If the processing of a form is idempotent (i.e. it has no lasting observable effect on the state of the world), then the form method should be GET. Many database searches have no visible side-effects and make ideal applications of query forms.
Characteristics of GET:
·         Use GET for safe actions and POST for unsafe actions.
·         GET requests can be cached
·         GET requests can remain in the browser history
·         GET requests can be bookmarked
·         GET requests can be distributed & shared
·         GET requests can be hacked
When to use POST
If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST.
·         Use POST when dealing with long requests – if you’re sending large amounts of data, or sensitive data over HTTPS, you will want to use POST. Some browser such as Internet Explorer place a limit on the URL string so this may break the action of some forms if you use GET.
You may consider using POST for the following actions:
·         Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles
·         Providing a block of data, such as the result of submitting a form, to a data-handling process
·         Extending a database through an append operation
·         Annotation of existing resources
GET vs POST in AJAX calls
Unless you are sending sensitive data to the server or calling scripts which are processing data on the server it is more common to use GET for AJAX calls. This is because when using XMLHttpRequest browsers implement POST as a two-step process (sending the headers first and then the data). This means that GET requests are more responsive – something you need in AJAX environments! Because “Ajax” requests are subject to the same origin policy there is limited security risks when using GET instead of POST. Use GET to “GET” information from the server such as loading a JavaScript file (AJAX shorthand function $.getScript() can be used to do this) or loading a JSON file (AJAX shorthand function $.getJSON() can be used to do this).
jQuery AJAX Functions that use GET as default: $.get(), $.getScript()$.getJSON().load()
jQuery AJAX Functions that use POST as default: $.post()
Example GET AJAX Call – Calling a PHP script to get the number of twitter followers.
1
2
3
4
5
6
7
8
9
10
11
12
13
$.ajax({
  url: ‘/Controllername/ActionName’,
  type: 'GET',
  data: {Id:$(‘#Id’).val()},
  success: function(data) {
    //called when successful
    $('#ajax-results').html(data);
  },
  error: function(e) {
    //called when there is an error
    //console.log(e.message);
  }
});
Example POST AJAX Call – Submitting a login form.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var $form = $("#myForm");
    var url = $form.attr("action") + "?" + $form.serialize();
    $("#" + id).html(url);

$.ajax({
    type: "POST",
    url: action,
    data: $form,
    success: function(response)
    {
        if(response == 'success')
            $("#myForm").slideUp('slow', function() {
                $("#msg").html("<p class='success'>You have logged in successfully!</p>");
            });
        else
            $("#msg").html("<p class='error'>Invalid username and/or password.</p>");
    }
});
Further Readings
Form Submission Example
This example doesn’t really apply to AJAX as these requests happen behind the scenes but may help you understand further what is happening between the different request types.
When using GET a HTTP request is generated and passes the data to the web server as a set of encoded parameters appended to the URL in a query string.
For instance, it would be a bad idea to use GET for a login form submission as the login details would show in the address bar.
1
2
GET /login.php?username=user&amp;password=12345 HTTP/1.1
Host: domain.com
But if we used POST the parameters would be passed within the body of the HTTP request, not in the URL. This would happen behind the scenes between the browser and the web server.
1
2
3
POST /login.php HTTP/1.1
Host: domain.com
username=user&amp;password=12345

GET Caching
GET is intended to be used when you are reading information to display on the page. Browsers will cache the result from a GET request and if the same GET request is made again then they will display the cached result rather than rerunning the entire request.

$.ajax() Performs an asynchronous HTTP (Ajax) request basically this is a method of jquery which internally uses xmlhttprequest object of JavaScript as asynchronous communicator which supports cross browser also.

There is lots of confusion in some of the function of jquery like $.ajax, $.get, $.post, $.getScript, $.getJSON that what is the difference among them which is the best, which is the fast, which to use and when so below is the description of them to make them clear and to get rid of this type of confusions.
As their names imply, get() uses the HTTP GET protocol and post() uses the POST protocol.

$.get() function is a shorthand Ajax function, which is equivalent to below expression, Uses some limited criteria like Request type is GET. In $.get() function there is no any error callback only you can track succeed callbackand there no standard setting supported like beforeSend, statusCode, mimeType etc, if you want to customize use $.ajax(). 

get: 
function(url, data, callback, type) {
 if ($.isFunction(data)) {
     callback = data;
     data = null;
 }

 return $.ajax({
       type: "GET",
       url: url,
       data: data,
       success: callback,
       dataType: type
     });
}
$.post() function is a shorthand Ajax function, which is equivalent to below expression, Uses some limited criteria like Request type is POST. In $.post() function there is also no any error callback only you can track succeedcallback and there no standard setting supported like beforeSend, statusCode, mimeType etc, if you want it use $.ajax(). 

post: function(url, data, callback, type) {
    if ($.isFunction(data)) {
        callback = data;
        data = {};
    }

    return $.ajax({
        type: "POST",
        url: url,
        data: data,
        success: callback,
        dataType: type
    });
}
 
$.getScript() function is a shorthand Ajax function (internally use $.get() with data type JSON), which is equivalent to below expression, Uses some limited criteria like Request type is GET and data Type is script.

$.getJSON() function is a shorthand
 Ajax function (internally use $.get() with data type script), which is equivalent to below expression, Uses some limited criteria like Request type is GET and data Type is json.



getScript: function(url, callback) {
     return $.get(url, null, callback, "script");
}
getJSON: function(url, data, callback) {
      return $.get(url, data, callback, "json");
}

And in both of
 the function ($.getScript(), $.getJSON()) there is also no any error callback only you can track succeed callback and there no standard setting supported like beforeSend, statusCode, mimeType etc, if you want it use $.ajax().

Wednesday, 1 January 2014

jQuery AJAX with Page Method example in ASP.NET

This article gives you step by step example for implementing WebMethod and calling it through jQuery.ajax() method.
This example will read data from Customer table of Northwind database. You can download Northwind database . Depending on selected Country value of DropDown, Customer details will be render if jQuery.ajax() call returns success.

jQuery.Ajax()

jQuery library functions and methods has capabilities to load data from server without a browser page refresh. jQuery.Ajax() performs an asynchronous http request. This method can handle response type of xml, json, script or html. If you are making a request to other domain datatype jsonp should be used. You can perform asynchronously GET, POST, PUT or DELETE methods on server using jQuery.Ajax().

Implementing PageMethod with jQuery.Ajax() in ASP.NET

  1. jQueryAJAX solution

    Create new solution of ASP.NET. Open visual studio click on File -> New -> Project -> ASP.NET Web Application name it as jQueryAjax and click Ok.
  2. Design Customer page

    Open Default.aspx or create new page with name Customer.aspx. In this step we will add a DropDownList control to give user to select particular Country. You can also try with jQuery
    We will also design a table object which will display Customer details on selection of Country. The jQuery change event of DropDownList will be used to add rows to table object.
    Add below html in BodyContent ContentPlaceHolder of Default.aspx.
    <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
        <div>
        Country:
        <asp:DropDownList ID="ddlCountry" runat="server">
            <asp:ListItem Text="Brazil" Value="Brazil"></asp:ListItem> 
            <asp:ListItem Text="France" Value="France"></asp:ListItem> 
            <asp:ListItem Text="Germany" Value="Germany"></asp:ListItem> 
            <asp:ListItem Text="Spain" Value="Spain"></asp:ListItem> 
            <asp:ListItem Text="USA" Value="USA"></asp:ListItem> 
            <asp:ListItem Text="UK" Value="UK"></asp:ListItem> 
            <asp:ListItem Text="Mexico" Value="Mexico"></asp:ListItem> 
        </asp:DropDownList> 
        </div>
        <br />
        <div>
        <table id="tblCustomers" class="tblCustomers" >            
            <thead>
                <tr>
                    <th align="left" class="customerth">CustomerID</th>    
                    <th align="left" class="customerth">CompanyName</th>    
                    <th align="left" class="customerth">ContactName</th>    
                    <th align="left" class="customerth">ContactTitle</th> 
                    <th align="left" class="customerth">City</th>
                    <th align="left" class="customerth">Phone</th>  
                </tr>
            </thead> 
            <tbody>
                
            </tbody> 
        </table>        
        </div>     
    </asp:Content>
    
                
  3. Apply css to Customer table

    Open Site.css from Styles folder and add below styles to it. These styles are applied to table, table header and table row objects.
        .tblCustomers
        {
            font-family: verdana,arial,sans-serif; 
            font-size:11px;
            color:#333333;
            border-width: 1px;
            border-color: #666666; 
            border-collapse: collapse;    
        }
    
        .customerth
        {
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #666666; 
            background-color: #dedede;   
        }
    
        .customertd
        {
            border-width: 1px; 
            padding: 8px; 
            border-style: solid; 
            border-color: #666666; 
            background-color: #ffffff;  
        }
                
  4. Customer Entity

    Add new class as Customer.cs. This class will be used to hold customer details. jQuery.ajax() method will get array of Customer object.
    Add below properties to Customer.cs
        public class Customer
        {
            public string CustomerID { get; set; }
            public string CompanyName { get; set; }
            public string ContactName { get; set; }
            public string ContactTitle { get; set; }
            public string City { get; set; }        
            public string Phone { get; set; }
        }
            
  5. PageMethod for jQuery.Ajax()

    Open codebehind file of Default.aspx page. In this file we will add a PageMethod which takes country as input parameter and return array of Customer object.
    It makes a database call to SQL Server and get customer details depending on provided country.
    Add below code in Default.aspx.cs file. Notice that we have added [System.Web.Services.WebMethod] for GetCustomers method which allows access to methods by scripting method.
    [System.Web.Services.WebMethod]
    public static Customer[]  GetCustomers(string country)
    {
        List<Customer> customers = new List<Customer>();
        string query = string.Format("SELECT [CustomerID], [CompanyName]," +
                 " [ContactName], [ContactTitle]," +
                 "[City], [Phone] FROM [Customers] " +
                   "WHERE Country LIKE '%{0}%'", country);
    
        using (SqlConnection con =
                new SqlConnection("your connection string"))
        {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                con.Open(); 
                SqlDataReader reader = cmd.ExecuteReader();
    
                while (reader.Read())
                {
                    Customer customer = new Customer();
                    customer.CustomerID = reader.GetString(0);
                    customer.CompanyName = reader.GetString(1);
                    customer.ContactName = reader.GetString(2);   
                    customer.ContactTitle = reader.GetString(3);
                    customer.City = reader.GetString(4);
                    customer.Phone = reader.GetString(5);
                    customers.Add(customer);   
                }
            }
        }
                
        return customers.ToArray();
    }
                
  6. jQuery.Ajax()

    In this step we will call PageMethod created in previous step. Create a new JavaScript file by open Solution Explorer -> right click on Scripts folder -> Select Add -> New Item -> Choose JScript -> Name it as Customer.js and click Ok
    Add function for ddlCountry DropDownList's change event. Whenever user will change selection of country, PageMethod will be called through jQuery.Ajax(). If call is successfull it will read Customer details and add each customer as table row to tblCustomers.
    $(document).ready(function () {
    
        $("#MainContent_ddlCountry").change(function () {
            
            $("#tblCustomers tbody tr").remove();
    
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetCustomers",
                data: '{country: "' + $(this).val() + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    response($.map(data.d, function (item) {
                        var rows = "<tr>"
                        + "<td class='customertd'>" + item.CustomerID + "</td>"
                        + "<td class='customertd'>" + item.CompanyName + "</td>"
                        + "<td class='customertd'>" + item.ContactName + "</td>"
                        + "<td class='customertd'>" + item.ContactTitle + "</td>"
                        + "<td class='customertd'>" + item.City + "</td>"
                        + "<td class='customertd'>" + item.Phone + "</td>"
                        +"</tr>";
                        $('#tblCustomers tbody').append(rows);
                    }))
                },
                failure: function (response) {
                    var r = jQuery.parseJSON(response.responseText);
                    alert("Message: " + r.Message);
                    alert("StackTrace: " + r.StackTrace);
                    alert("ExceptionType: " + r.ExceptionType);
                }
            });
        });
    });
    
    
    $("#tblCustomers tbody tr").remove(); removes existing rows from table object.
    Url is mentioned as "Default.aspx/GetCustomers" which indicates where your PageMethod exists.
    PageMethod takes country as input parameter which is mentioned with data property of $.ajax.
    success: function (data) { } will execute when PageMethod executes successfully. It add row for each customer record.
    failure: function (response) { } will execute if there is any error in execution of PageMethod and gives details of error.
  7. Add reference to script files

    Open Site.Master file and add reference to script file in head tag of Master page.
    Your head tag will look like this
    <head id="Head1" runat="server">
        <title></title>
        <link href="~/Styles/Site.css"
             rel="stylesheet" type="text/css" />
        <script language="javascript" type="text/javascript"
             src="Scripts/jquery-1.4.1.min.js"></script>  
        <script language="javascript"  
            type="text/javascript" src="Scripts/Customer.js"></script>  
        <asp:ContentPlaceHolder ID="HeadContent" runat="server">
        </asp:ContentPlaceHolder>
    </head>
    

read customer from server by jQuery Ajax