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

Simple AJAX POST Form and AJAX Fetch Link to Modal Popup

, 17 Dec 2012
Rate this:
Please Sign up or sign in to vote.
Post a form using AJAX and get/load your links to an AJAX modal popup. Sample for basic XML AJAX chatter.

Introduction 

Many times when working with a parent child type UI, we want to show the details of child objects on a modal popup fetched only on request (i.e., through AJAX). And we might want to post form data using AJAX. Here is a simplified plug-in to help us post a form using AJAX and load the response in a Modal dialog. It also helps us to retrieve sub pages (or child details) in a modal dialog using AJAX.

(This project uses AJAX to post data and fetch returned values. The data is stored in an XML database using .NET XmlSerializer. This demo can be customized to be used as a simple AJAX chatter with an XML database.)

Background

jQuery makes it easy to get and post data using AJAX. We do have many AJAX based modal popups. This article creates a simplified plug-in to achieve the same. The emphasis is on simplifying fetching and posting of data using AJAX.

Running the demo

  • Open the project as a website in Visual Studio. Open Index.htm. Build and Run. or
  • Host the contents of dmo.zip into a new website in your IIS configured as an ASP.NET application.

Using the code

The first thing we need to do is include jQuery, jQuery-UI plug-in, and our AjaxLinks plug-in in your page.

<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<link href="Styles/jquery.ui.css" rel="stylesheet" type="text/css" />
<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>
<script src="Scripts/AjaxLinks.js" type="text/javascript"></script>

Now to fetch a link into a modal popup through AJAX we should decorate that hyperlink with the class="AjaxGet" attribute. To post a form using AJAX we will need to decorate that form with the class="AjaxPost" attribute.

Here is how the code works:

AjaxPostForm

Here is our AjaxPostForm function. This function attaches itself to the submit event of all the forms which have been decorated with the class="AjaxPost" attribute. As explained in the comments below, this function:

  1. Attaches itself to the submit event of forms decorated with the class="AjaxPost" attribute.
  2. Stops the normal posting of the form.
  3. Retrieves the target action of the form into a variable url.
  4. Retrieves the values from the form and serializes them with help of the jQuery $form.serialize() function.
  5. Performs AJAX POST using the jQuery AJAX function ($.ajax(...)).
    1. If the result is successful, creates a modal dialog and displays the response HTML of the target page.
    2. If the result is unsuccessful, creates a modal to show the error screen.
AjaxPostForm: function () {
    /* attach a submit handler to the form */
    $("form.AjaxPost").submit(function (event) {

        /* stop form from submitting normally */
        event.preventDefault();

        /* get some values from elements on the page: */
        var $form = $(this);


        //Gets the target of the form. And Serialize Form data so that it can be posted using Ajax
        var url = $form.attr('action');
        var pdata = $form.serialize()


        $.ajax({
            type: "POST",
            url: url,
            data: pdata,
            success: function (resp) {
            //Upon success, load the response of the Posted form
            //into the display Div and create a Modal Dialog for it.
                var $jAlrtSuccess = $('<div />');
                $jAlrtSuccess.html(resp);
                $($jAlrtSuccess).dialog(AjaxLinks.postResponseDivParam);
            },
            error: function (xhr, status, error) {
                var $jAlrtError = $('<div>' + xhr + '</div>');
                $($jAlrtError).dialog(AjaxLinks.postResponseDivParam);
            }
        });
    });
    return false;
}

AjaxGetLink

And here is our AjaxGetLink function. This function attaches itself to the click event of the hyperlinks decorated with the class="AjaxGet" attribute. As explained in the comments, this function:

  1. Attaches itself to the click event of hyperlinks decorated with the class="AjaxGet" attribute
  2. Finds out the target of this link using the code and saves it in the variable actionurl
  3. Sets up the width, height and position of the target modal popup which will display as content, the HTML retrieved from the actionurl
  4. Performs the Get operation using the jQuery AJAX function  ($.ajax(...))
    1. On success displays the response HTML into a modal dialog
    2. On error displays the error as a modal dialog
AjaxGetLink: function() 
{
    $('a.AjaxGet').click(function () {
        var pdata = $(this).attr('data-value');
        
        //Create an empty dialog first. This will be destroyed once data is received
        var $divNm = $('<div>Loading. Please wait....</div>').appendTo(
            $(this)).dialog();//.dialog(modalOptions); //'#' + $(this).attr('data-name');            
        var actionurl = $(this).attr('href');
        
        var horizontalCenter = Math.floor(screenWidth/2);
        var verticalCener = Math.floor(screenHeight/2);

        //Setting the position and width of the 
        //Popup dialog to open to display response once contents of target Link are fetched using Ajax
        var myDialogX = 20; 
        var myDialogY = verticalCener-300; 
        var modalWidth = screenWidth -80;

        var modalOptions = { height:600, width: modalWidth, autoOpen: true, 
            modal: true, zIndex: 3999, position: [myDialogX,myDialogY],
            buttons: {Close: function() {$( this ).dialog( "close" );}}  };
        
        var dialogOpts = {
            type: "GET",
            url: actionurl+"?bustcache="+ new Date().getTime(),
            data: pdata,
            success: function (resp) {
            //Upon success, load the fetched data into the display Div and create a Modal Dialog for it.
                $divNm.html(resp);
                $divNm.dialog("destroy");
                $divNm.dialog(modalOptions);
                return false;
            },
            error: function (xhr, status, error) {
                $divNm.html(xhr.responseText + status.toString());
                $divNm.dialog("destroy");
                $divNm.dialog(modalOptions);
                return false;
            }
        };
        $.ajax(dialogOpts);
        return false;
    });
},

Points of interest

For ASP.NET MVC we have quite a number of awesome helpers. If we want to make a form AJAX based, we can simply begin the form as Ajax.BeginForm() instead of Html.BeginForm() and ASP.NET helpers will take care of generating the necessary AJAX code for us.

The XML persister class

Our persistence class, Persister is a cut down version of XML persister from My Web Pages StarterKit project.

This class can be useful for persisting your settings to XML config files. In our case, we are using it to persist our posts data into the XML database (App_Data/Posts.config). It serializes and deserializes XML objects and abstracts a lot of functionality for you. All you need to do is:

  1. Provide the location of your XML file in the constructor.
  2. Provide the type of the object to persist in the XML.
  3. public class Persister<T>
    {
        private string _dataFileName;
        private List<T> _objList;
    
        public List<T> objList
        {
            get { return (_objList); }
        }
    
        public Persister(string dataFileName)
        {
            //
            // TODO: Add constructor logic here
            //
            this._dataFileName = HttpContext.Current.Server.MapPath(
                 string.Format("~/App_Data/{0}", dataFileName));
            this._objList = Activator.CreateInstance<List<T>>();
        }
    
                public void save()
        {
            lock (_dataFileName)
            {
                using (FileStream writer = File.Create(_dataFileName))
                {
                    XmlSerializer serializer = new XmlSerializer(_objList.GetType());
                    serializer.Serialize(writer, _objList);
                }
            }
        }
    
        public void load()
        {
            if (File.Exists(_dataFileName))
            {
                lock (_dataFileName)
                {
                    using (FileStream reader = File.Open(_dataFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
                        _objList = (List<T>)serializer.Deserialize(reader);
                    }
                }
            }
            else
            {
                _objList = new List<T>();
                save();
            }
        }
    }

    Here is how we use it to persist our Posts objects:

    //Inside posted.aspx.cs file 
    //Pass the type of object ("Posts") and Name of the datafile to be used, to the constructor of Persister
    Persister<Posts> currentPosts = new Persister<Posts>(_dataFileName);
    
    //Load the objects of type Posts from the current Posts config
    currentPosts.load();
    _posts = currentPosts.objList;
    
    if (Request.RequestType == "POST")
    {
        //Fetch the request data
        string strName = Request.Form["txtName"];
        //....
        //Create a Posts object and assign values
        Posts post = new Posts();
        post.Name = strName;
        //....
        //Add it to the current loaded list and save the list using persister
        _posts.Add(post);
        currentPosts.save();
    }

History

Initial post with introduction to AjaxGet Link and AjaxPost Form.

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

 
Question[My vote of 1] Next time provide a solution and use namespaces Pinmembermsdevtech30-Nov-12 1:40 
AnswerRe: [My vote of 1] Next time provide a solution and use namespaces Pinmemberokdone17-Dec-12 21:58 

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 | Mobile
Web03 | 2.8.140821.2 | Last Updated 18 Dec 2012
Article Copyright 2012 by amitthk
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid