;

Javascript AJAX

Modern web technology is about javascript for programming the actual browser to make it an active tool instead of just a passive display. AJAX is one of the most useful functions of javascript, because it allows the page to actively get new content. I like using AJAX. It is efficient and skips the request round trip, allowing a smoothness and responsiveness that makes for a great user experience. To best use AJAX, I have developed some code that sends a standard form of a JSON message and incorporates multiple Command design patterns on the client and server. It is not complicated, but it is highly developed and will solve almost any AJAX requirement as well as gracefully handling errors. For your pervue...



Search For:
style="display:inline;" disabled="disabled">

 

This client code:

script>
    alert('Modernizer says=' + Modernizr.mq('only all and (max-width: 767px)') + '...');
    $("#idbtnPast").on('click', function () { doAjax('idbtnPast') });
    $("#idbtnPresent").on('click', function () { doAjax('idbtnPresent') });
    $("#idbtnFuture").on('click', function () { doAjax('idbtnFuture') });
function doAjax(sSource) {
    var sValue = '';
    if ((sSource == 'idbtnPast') || (sSource == 'idbtnPresent') || (sSource == 'idbtnFuture'))
        sValue = $('#' + sSource.replace('idbtn', 'idtext')).val();
    // else - error
    if (sValue == '')
        doAlert("A Name must be entered for that request.", 0);
    else {
        var sError = ""; // error should not happen here
        var sData = { id: sSource, error: sError, request: sValue }; 
        doAJAX1(sData);
    }
}
function doAJAX1(sData) {
    var objData = { sMessage: JSON.stringify(sData) };
    $.ajax({
        type: "POST",
        url: '/ProductSG3/AnswerAJAX1',
            data: objData, // Just send some text and parse it there to do whatever is needed
            dataType: "text", // data type that will be returned
            timeout:3000, // page configurable
            success: onSuccess,
            error: function (jqXHR, textStatus) {
                if (textStatus == 'timeout') 
                    alert('Failed from timeout');
                else
                    alert('An error occurred.');
            }
        });
    }
	
// Receives JSON message like {'id':'idbtnPast','error':'', 'content':'I could be text, html or more JSON' }
    function onSuccess(data) {
        var oParser = eval('(' + data + ')');
        if (oParser.error != '') {
            $('#iddivErrorMsg').html(oParser.error);
        }
        else {
            if (oParser.id == 'idbtnPast') {
                $('#iddivPast').html(oParser.content);
            }
            else if (oParser.id == 'idbtnPresent') {
                $('#iddivPresent').html(oParser.content);
            }
            else if (oParser.id == 'idbtnFuture') {
                $('#iddivFuture').html(oParser.content);
            }
            // else - error
        }
    }
    function onError()
    { alert('An error occurred.'); } 
/script>
            

 


 

This Server code:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AnswerAJAX1(JStringsSG data) // JStrings is just class containing string sMessage
{
    string strError = String.Empty;
    string strId = String.Empty;
    string strRequest = String.Empty;
    string strHTML = String.Empty;
    Dictionary dictInput = new Dictionary();
    Dictionary dictOutput = new Dictionary();
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    try
    {
        dictInput = serializer.Deserialize>(data.sMessage);
    }
    catch (Exception ex)
    {
        strHTML = "<li id='-1' class='clFailed' title='There was a problem with the search request' >
                    There was a problem with the search request</li>";
        dictOutput.Add("id", strId);
        dictOutput.Add("error", strError);
        dictOutput.Add("content", strHTML);
    }
    //strError = dict["error"]; // Going to ignore error from client
    if (String.IsNullOrEmpty(strHTML) == true)
    {
        if (dictInput.ContainsKey("request") == true) // Should exist from client
            strRequest = dictInput["request"];
        if (dictInput.ContainsKey("id") == true)
        {
            strId = dictInput["id"];
            if (strId == "idbtnPast")
                strHTML = strTellThePast(strRequest);
            else if (strId == "idbtnPresent")
                strHTML = strTellThePresent(strRequest);
            else if (strId == "idbtnFuture")
                strHTML = strTellTheFuture(strRequest);
            else // error
                strError = "Error: Source Id was invalid:" + strId + "."; // unlikly error 
        }
        else
            strError = "Error:Request did not include a source Id.";
        dictOutput.Add("id", strId);
        dictOutput.Add("error", strError);
        dictOutput.Add("content", strHTML);
    }
    //var jName = Json(dictOutput);
    return Json(dictOutput, JsonRequestBehavior.AllowGet);
}
protected string strTellThePast(string strName)
{
    return strName + ", your past was an inspiration to millions. You changed the world.";
}
protected string strTellThePresent(string strName)
{
    return strName + ", your present is a challenge that you will overcome with perseverience and tenacity.";
}
protected string strTellTheFuture(string strName)
{
    return strName + ", your future is obviously unknown, but I am sure it will be illustrious.";
}
// It's just a string, but it needs to be passed as an object for the code.
public class JStringsSG
{
    public string sMessage { get; set; }
}