Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to Submit Multiple Form Using jQuery and Ajax

In this article we will see how to implement multiple forms with jQuery and JavaScript code asynchronously by Ajax, via simple codes.

Forms are largely used on a number of websites to collect data that may be required to be obtained from a user. As such, forms on the web can be largely prepared using plenty of methods. One for example would be HTML, and that is used to create simple forms.

If you have noticed carefully, of late, Ajax forms seem to have become largely popular in website development. Now, it is certainly not surprising to see this kind of a trend considering that the use of Ajax implies certain advantages. Also, coupled with the likes of jQuery, the entire process also becomes a whole lot easier to carry out.

In the example that follows, we shall try to achieve this.

How are we going to implement this?

In order to implement the submission of multiple forms demo, we are going to use Ajax, jQuery, JavaScript, HTML and PHP.

Why use jQuery?

Ajax forms can be used with many other methods. However, here we have chosen to go with jQuery for quite a number of reasons. It is definitely true that jQuery offers certain advantages.

You must already be aware that jQuery is a JavaScript library that is largely used for cross platform usage and also basically meant to simplify the overall scripting process on the client-side. Also, being free and open-sourced, there is no problem in procuring it for use. On the other hand, it also happens to be the most popular library on JavaScript that is used at present.

  • jQuery simplifies things to a great deal. Compared to the standard JavaScript libraries that are present, jQuery is easy on the implementation aspect.
  • It has a large library with elements that you can use.
  • It is extensible with the help of numerous plugins.
  • Offers great support for Ajax, which is most important thing from our perspective when it to comes to this particular lesson.

What does Ajax offer?

Ajax just happens to be a group of co-related technologies on the web that can help with the creation of client-side asynchronous applications that capable of sending and receiving data in the background. This also means that it doesn’t get in the way of the display and behavior of the page that exists. As such, it stands for asynchronous JavaScript and XML.

The pros of using Ajax –

  • Interactivity is way better in Ajax and that is primarily the reason that developers have been using it on their sites. It allows for quicker data exchange without the need to reload the entire page.
  • Ajax also offers very easy navigation.
  • A number of applications that solve many different purposes can be handled in a single web page, thus offering great compactness.

Code to implement simple form in HTML

Listing 1: Simple form

 
<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
    First Name: <input type="text" name="fname" value =""/> <br/>
    Last Name: <input type="text" name="lname" value ="" /> <br/>
    Email : <input type="text" name="email" value=""/> <br/>
</form>

Figure 1 – Displaying submit section

Listing 2: Form submission using jQuery and Ajax

//implementation of callback handler for form submission
$("#ajaxform").submit(function(e)
{
    var postdata = $(this).serializeArray();
    var formurl = $(this).attr("action");
    $.ajax(
    {
        url : formurl,
        type: "POST",
        data : postdata,
        success:function(data, textStatus, jqXHR) 
        {
            //data: returning of data from the server
        },
        error: function(jqXHR, textStatus, errorThrown) 
        {
            //if fails      
        }
    });
    e.preventDefault(); // default action us stopped here
    e.unbind(); //unbind. allows for stopping multiple form submission
});
 
$("#ajaxform").submit(); //Submitting  the form 

Figue 2 – Simple form page

Code to implement multiple form submission

In this following example we will check how multiple forms can be submitted. Following code will show the JavaScript section.

Listing 3: This is the code for JavaScript

<script type="text/javascript" src="jquery.js"></script>
 <script type="text/javascript" >
 $(document).ready(function()
 {
 $(".comment_submit").click(function(){
 var element = $(this);
 var id = element.attr("id");
 var test = $("#textboxcontent"+id).val();
 var dataString = 'textcontent='+ test + '&com_msgid=' + id;
 if(test=='')
 {
 alert("Go Ahead and Enter Some Text");
 }
else
{
 $("#flash"+id).show();
 $("#flash"+id).fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle"> loading.....');
 $.ajax({
 type: "POST",
 url: "insertajax.php",
 data: dataString,
 cache: false,
 success: function(html){
 $("#loadplace"+id).append(html);
 $("#flash"+id).hide();
 }
 });
 }return false;});});
 </script> 

Now the following section will describe the HTML and PHP code.

Listing 4: This consists of the HTML and PHP code

<div id="loadplace<?php echo $msg_id; ?>"></div>
 <div id="flash<?php echo $msg_id; ?>"></div>
 <div class='panel' id="slidepanel<?php echo $msg_id; ?>">
 <form action="" method="post" name="<?php echo $msg_id; ?>">
 <textarea id="textboxcontent<?php echo $msg_id; ?>" ></textarea><br />
 <input type="submit" value=" Comment_Submit " 
 class="comment_submit" id="<?php echo $msg_id; ?>" />
</form>
</div>

The $msg_id portion that you see has been obtained from the database.

Listing 5: ajaxin.php file

 
 <?php
if(isSet($_POST['text_content']))
 {
 $txtcontnt=$_POST['text_content'];
// Some SQL data values insert into comments table
}
?>
<div class="load_comment">
 <?php echo $txtcontnt; ?></div> 

Submission of multi-part form or data

While we have demonstrated the implementation of multiple form submission using jQuery and Ajax, another application related to this can be the submission of multi-part form or data-form. The submission of HTML forms with file uploads isn’t a very simple task, considering that no direct API to send files is present. Thus, using FormData API in HTML5 for reading and $.ajax() API for submission of data makes it possible.

Listing 6: HTML form that can support file uploads

<form name="multiform" id="multiform" action="multiformsubmit.php" method="POST" enctype="multipart/form-data">
    Name: <input type="text" name="name"  value="Ron"/> <br/>
    Age :<input type="text" name="age"  value="14" /> <br/>
    Img :<input type="file" name="photo" /><br/>
</form>

The code below can upload data and files without the need to refresh the page.

Listing 7: Showing upload without refresh

//Callback handler that has been implemented for form submit event
$("#multiform").submit(function(e)
{
 
    var formobj = $(this);
    var formurl = formobj.attr("action");
    var formdata = new FormData(this);
    $.ajax({
        url: formurl,
    type: 'POST',
        data:  formdata,
    mimeType:"multipart/form-data",
    contentType: false,
        cache: false,
        processData:false,
    success: function(data, textStatus, jqXHR)
    {
 
    },
     error: function(jqXHR, textStatus, errorThrown) 
     {
     }          
    });
    e.preventDefault(); //Prevention of default action. 
    e.unbind();
}); 
$("#multiform").submit(); //Submitting the form 

Following is the output of multi-part form submission.

Figure 3 – Multipart form page

Listing 8: Support for all browsers

The code defined in Listing 7 may not always support all browsers, mainly older ones. So, Listing 8 does that by utilizing the hidden iframe method.

$("#multiform").submit(function(e)
{
    var formobj = $(this);
    var formurl = formobj.attr("action");
 
    //generate a random id
    var  iframeID = 'unique' + (new Date().getTime());
 
    //creation of an empty iframe
    var iframe = $('<iframe src="javascript:false;" name="'+iframeID+'" />');
 
    //hide it
    iframe.hide();
 
    //set form target to iframe
    formObj.attr('target',iframeID);
 
    //Add iframe to body
    iframe.appendTo('body');
    iframe.load(function(e)
    {
        var docu = getDoc(iframe[0]); //getting the iframe document
        var docroot = docu.body ? docu.body : docu.documentElement;
        var data = docroot.innerHTML;
 
        // returning of data from the server
    });
 
}); 
$("#multiform").submit();

This is the code for the combined method that brings support for both, old and new browsers under the belt.

Listing 9: Showing support for old and new browser

function getdoc(frame) {
     var docu = null;
 
     // IE8 cascading access check
     try {
         if (frame.contentWindow) {
             docu = frame.contentWindow.document;
         }
     } catch(err) {
     }
 
     if (docu) { // successful in getting content
         return docu;
     }
 
     try { // simple checking can throw in IE8 under SSL or mismatched protocol
         docu = frame.contentDocument ? frame.contentDocument : frame.document;
     } catch(err) {
         // last attempt
         docu = frame.document;
     }
     return docu;
 }
$("#multiform").submit(function(e)
{
 
    var formobj = $(this);
    var formurl = formobj.attr("action");
 
    if(window.FormData !== undefined)  // for HTML5 browsers
    {
 
        var formdata = new FormData(this);
        $.ajax({
            url: formurl,
            type: 'POST',
            data:  formdata,
            mimeType:"multipart/form-data",
            contentType: false,
            cache: false,
            processData:false,
            success: function(data, textStatus, jqXHR)
            {
 
            },
            error: function(jqXHR, textStatus, errorThrown) 
            {
 
            }           
       });
        e.preventDefault();
        e.unbind();
   }
   else  //for older browsers
    {
        //generation of any random id
        var  iframeID = 'unique' + (new Date().getTime());
 
        //create an empty iframe
        var iframe = $('<iframe src="javascript:false;" name="'+iframeID+'" />');
 
        //hide it
        iframe.hide();
 
        //set form target to iframe
        formObj.attr('target',iframeID);
 
        //Add iframe to body
        iframe.appendTo('body');
        iframe.load(function(e)
        {
            var docu = getdoc(iframe[0]);
            var docroot = docu.body ? docu.body : docu.documentElement;
            var data = docroot.innerHTML;
            //data is returned from server.
 
        });
 
    }     
});
$("#multiform").submit();

Conclusion

If you take a look at the given examples above, you’ll clearly how the process of submitting of simple and then multiple forms that has been demonstrated. Also, we have used the likes of jQuery and Ajax to again implement another slightly different feature, that being multipart form/data submission. Support has also been provided to browsers that generally belong to the older lot by making use of the ifarme method in this case.

The use of Ajax has been preferred as it helps in better interaction between the server and the webpage in question.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login