Uploading Files with AJAX Multiple Forms

by Owais Mushtaq

If we have a set of forms from which we have to get data and also delete some files that we don’t want sent to server, we can upload files using Ajax Multiple Forms.

The HTML file list does not allow us to edit, it’s a read-only list, however it allows us to ’empty list’ but does not allow us to delete a specific set of files in a list so we can’t delete specific files in a list.

""" Note on each file i mark delete in Template i just create
 a hidden element with name “del_files” but with value as the
 name of file that i marked as deleted """
var delfiles = []; # A list that holds files marked deleted in Template(HTML page/Form).
$("input[name=del_files]").each(function()
{
delfiles.push(this.value);
});
 var send_data = new FormData() #create a FormData object
 var ifile = $('.i_file'); #this gets the filelist in html input type file.

Below are the lines of code that iterates through each file list element and checks whether the filename is same as those in deleted list ‘delfiles’.

<strong><span style="font-weight: 400;">for(var i=0;i<ifile.length;i++)</span></strong>
    {
       var leng_files = ifile[i].files.length;
       for(var j=0;j<leng_files;j++)
           {
              var file = ifile[i].files[j];
              “””
              a simple method used for comparing the file is in deleted files and also discards the file that exceeds 25MB in size.
              ”””
              if (check_f(file,delfiles))
                  {
                      “””
                      if the function returns true the file is appended to formdata object.
                      ”””
                          send_data.append('localfile', file, file.name);
                      “””
                      The first parameter specifies the name of the data entry. This will form the key in the data payload. The second parameter specifies either a File that will be used as the value for the data entry. When appending a File you can also specify a filename, but this isn’t required.
                      “””
                  }
           }
    }

Function defines the method that returns true or false, function returns false if the file is in deleted file list or file size exceeds 25MB, else returns true.

function check_f(file,delfiles)
    {
       var size25 = 1073741824;#size in bytes
       for(var i=0;i<delfiles.length;i++)
           {
              if (file.name == delfiles[i])
                  {
                    return false;
                  }
              else if(file.size&gt;size25)
                  {
                   return false;
                  }
           }
       return true;
    }

The .serializeArray() method uses standard W3C rules for successful controls to determine elements it should include; in particular the element cannot be disabled and must contain a name attribute. No submit button value is serialized since the form was not submitted using a button. Data from file select elements is not serialized.
This method can act on a jQuery object that has selected individual form controls, such as <input>, <textarea>, and <select>. However, it is typically easier to select the <form> element itself for serialization. For more information please visit https://api.jquery.com/serializeArray/

var firstform = jQuery(document.forms['form_name1']).serializeArray(); # serialize first form
for (var i=0; i<firstform.length; i++)
    {
        send_data.append(firstform[i].name, firstform[i].value);
    }

var secondform = jQuery(document.forms['form_name2']).serializeArray();# serialize second form
for (var i=0; i<secondform.length; i++)
    {
    send_data.append(secondform[i].name, secondform[i].value);
    }
…. and so on you can serialize and append form data of as many forms as you wish.
#Now we have to send data through ajax.
sendajax(send_data, 'post', url, target);

#end of main method

Function definition Ajax call

function sendajax(data,type,url,target)
{
  $.ajax(
  {
    type:type,
    url : url,
    data : data,
    enctype: 'multipart/form-data',
    cache: false,
    contentType: false,
    success : function(response)
      {
        if (target !== null)
          {
            target_tag(response,target)
          }
      },
    error: function()
      {
      console.log('Error occured');
      }
  });
}

In the above blog, we learnt how we can send data from more than one form using Ajax, how we can create FormData object, use serializeArray method to get data from different forms, how to append data to FormData object and so on.  In the next blog I will show how we will use a progress bar in ajax for single or multiple forms. Stay tuned!

To learn more about

Contact Us

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Tools & Practices

Tools and Technologies we use at Applied

Contact us now

Popular Posts