Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

AJAX Example - jQuery and JavaScript

RSS
Modified on Wed, Jul 31, 2013, 9:49 AM by Administrator Categorized as (Favorites), ASP·NET MVC, JavaScript, jQuery, and Angular

Table of Contents [Hide/Show]


   AJAX Calls
      Client Code, AJAX
      Client Code, JSON
      Server Code
   Using an AJAX Form
      View Code
      JavaScript
      Server Code
   Without jQuery


AJAX Calls

Client Code, AJAX

$.ajax({
    type: "{ GET | POST }",
    url: "/Controller/Method",
    async: { false | true },
    datatype: 'json',
    data: { param1: value1, param2: value2 },
    success: function(data) {
        $.each(data, function(key, val) {
            // do something with each value
            }); /* each */
        }, /* success */
    error: function(xhr, ajaxOptions, statusDescription) {
        alert(statusDescription);
        } /* error */
}); /* ajax */

With the exception of the async parameter, the most common parameters can be remembered via the mnemonic device "dusted".
  • D = data
  • U = url
  • S = success
  • T = type
  • E = error
  • D = datatype

Notes
  • To trip the error function from server code, set the Response.StatusCode to 500, which indicates an internal server error, and DO NOT throw an exception.
  • Within the error function, the statusDescription parameter corresponds to the Response.StatusDescription value you set in your ASP.NET server code
  • Consider using the following server (controller) code to trap and bubble exceptions to the client code.

[HttpPost]
public JsonResult MyMethod(MyModel m)
{
    if (!ModelState.IsValid)
    {
        var response = (from ms in ModelState.Values
                        from err in ms.Errors
                        select err.ErrorMessage).ToList().FirstOrDefault();

        Response.StatusCode = 500;
        Response.StatusDescription = response;
        //return Json(response);
        return null;
    }

    m.SaveToDatabase()
    return Json("");

} 

Client Code, JSON

$.getJSON(
    url,
    { param1: value1, param2: value2 }, // optional
    function (data) {
        }
    )
    // optional success method
    .success(function(){
        })
    // optional error handler
    .error(function(){
        }); 

Server Code

[HttpGet, Authorize]
public JsonResult GetData(int regionID)
{
    IQueryable items = MyDataProvider.GetData(regionID);
    return Json(items, JsonRequestBehavior.AllowGet);
}

Using an AJAX Form

View Code

 @using (Ajax.BeginForm("Method", "Controller", new { }, new AjaxOptions() { HttpMethod="Post", 
OnSuccess="EditSuccess", OnFailure="EditFailure"  }))
{
. . .
} 


JavaScript

function EditSuccess(data) {
    $("#EditDialog").dialog('close');
    location.reload(true);
}

function EditFailure(ajaxData, msg, statusDescription) {
    // statusDescription here is whatever you set Response.StatusDescription to
    // in the server code
    alert(statusDescription);
}

Server Code

Notes
  • To trip the error function from server code, set the Response.StatusCode to 500, which indicates an internal server error, and DO NOT throw an exception.
  • Within the error function, the statusDescription parameter corresponds to the Response.StatusDescription value you set in your ASP.NET server code
  • Consider using the following server (controller) code to trap and bubble exceptions to the client code.

public ActionResult MethodName(MyViewModel model)
{
    . . .

    // Error condition
    if (ErrorCondition)
    {
        Response.StatusCode = 500;
        Response.StatusDescription = "ERROR MESSAGE GOES HERE";
        return null;
    }
    . . .
}

Without jQuery

The following is a sample HTML file that uses AJAX via the XMLHttpRequest object.

<html>
<head>
< script type="text/javascript">
function test()
{
    var div;
    div = window.document.getElementById("myDiv");
    div.innerText = "hello world";
}
var xmlhttp
function loadXmlDoc(url)
{
    xmlhttp = null

    //-- Mozilla, etc. ----------------------------------------------------------------
    if (window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest()
    }
    //-- IE ---------------------------------------------------------------------------
    else if (window.ActiveXObject)
    {
        try 
        { 
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP")
        } 
        catch (e) 
        {
            try 
            { 
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
            } 
            catch (e) {}
        }
    }

    //-- Make AJAX call ---------------------------------------------------------------
    if (xmlhttp != null)
    {
        xmlhttp.onreadystatechange = state_Change
        xmlhttp.open("GET", url, true)
        xmlhttp.send(null)
    }
    //else
    //{
    //    alert("Your browser does not support XMLHTTP.")
    //}
}

function state_Change()
{
    if (xmlhttp.readyState == 4) // 4 = loaded
    {
        var div;
        div = window.document.getElementById("myDiv");

        if (xmlhttp.status == 200) // 200 = OK
        {
            // handle xmlhttp.responseText
            div.innerText = xmlhttp.responseText;
        }
        else
        {
            div.innerText = "Problem retrieving XML data"
        }
    }
}
</script>
</head>
<body>
<input type="button" value="test" 
onclick='loadXmlDoc("http://www.yahoo.com");' />
<div id="myDiv"/>

</body>
</html>

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.