Click here to Skip to main content
Click here to Skip to main content

Submit a form using Ajax instead of Normal Post

, 26 Nov 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Post the page forms using Ajax intead of Normal Post (Like when using MVC)
Many times, we want to post our form using Ajax instead of Normal Post. So here is a script which is useful to achieve this. This is the changed version from the original Jquery website as this one POSTs the data to the server (We do have a GET version available at Jquery Website).
 
So, e.g. our Controller's action is something like this (this is C#):
 [HttpPost]
        public JsonResult SaveSettings(FormCollection collection)
        {
            string dValue = "=> " + collection[0] + "=> " + collection[1] + "=> " + collection[2] + "=> " + collection[3] + "=> " + collection[4] + "=> ";
            fassconf.Models.JsonResponse rslt = new Models.JsonResponse() { isSuccessful = true, errorMessage = "", responseText=dValue+"Information is Saved Now.", Id = "success" };
 
            return Json(rslt);
        }
 
And our View is something like this (The form is using Razor. It is a normal form):
<form action="/Test/SaveSettings" class="AjaxSubmit" method="post">    <ul>
    <li>Pclf<input type="text" name="pclf" id="pclf" /></li>
 
    <li>RF<input type="text" name="RF" id="RF" /></li>
    <li>IP<input type="text" name="IP" id="IP" /></li>
    <li>CF<input type="text" name="CF" id="CF" /></li>
    <li>RD<input type="RD" name="RD" id="RD" /></li>
        <li><button id="btnFrmPost1" >Post</button></li>
        </ul>
</form>
 
So here is our JavaScript which attaches Ajax Based Postback to our Form. The selection is done on the basis of class "AjaxSubmit". (We can do it using form Id also. But I'm using class selector here just in case you have multiple forms on your view and you might want to post all of them using AJAX. Smile | :)
 
//Of course we also need Jquery and Jquery UI scripts
    <script src="/Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script src="/Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>
 
/*When document is loaded, attach following function to the Onclick event of all the forms decorated with class=AjaxSubmit*/
 
    $(document).ready(function ($) {
        /* attach a submit handler to the form */
        $("form.AjaxSubmit").submit(function (event) {
 
            /* stop form from submitting normally */
            event.preventDefault();
 
            /* get some values from elements on the page: */
            var $form = $(this);
 
            var url = $form.attr('action');
            var data = $form.serialize()
//Here I call the ajax and post the data
            $.ajax({
                type: "POST",
                dataType: "json",
                url: url,
                data: data,
                success: function (resp) {
                    var jdata = eval(resp);
                    var $jAlrtSuccess = $('<div>' + jdata.responseText + '</div>');
/*On success, alert the appropriate message accordingly*/
                    $($jAlrtSuccess).dialog({modal:true});
                },
                error: function (xhr, status, error) {
 
                    var $jAlrtError = $('<div>' + xhr.responseText + '</div>');
/*On error, show us the RAW error what happened :( */
                    $($jAlrtError).dialog({modal:true});
 
                }
            });
        });
        return false;
    });

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

amitthk
Software Developer (Senior)
Singapore Singapore
I love programming, reading, and meditation. I like to explore management and productivity.
Follow on   Twitter

Comments and Discussions

 
GeneralOff Course PinprotectorAspDotNetDev25-Nov-11 17:58 
GeneralRe: Off Course Pinmemberokdone25-Nov-11 21:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141216.1 | Last Updated 26 Nov 2011
Article Copyright 2011 by amitthk
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid