Category Archives: Forms

Forms are a basic element of the HTML page. You use them to get the input from the user!

Uploading the files – HTML5 and jQuery way!

Download the Sample from Dropbox

Most of the websites are using HTML5 and jQuery plugins, to upload the files without the user to have to send a POST request to the server, which is not a likely way of uploading the files.

Old way of uploading files

In old days, people likes to create a simple HTML form, and assign the encytype to it, that would let them select a file and then they will click on the Submit button which would then take them to a new page, where they will be shown the message, “Your photos have been uploaded” – or an error message telling them that there was an error. This is a bit irritating and awkward, because the user uploaded more like 5 photos among with one got an error, and the remaining 4 were also discarded and the user was told after 2 minutes to upload the 4 photos only and not that one particular image. Sometimes, connection is lost and other stuff!

New ways of uploading the files

The web is changing, and there are a lot of new ways in which the user can upload the image or his any file to the server, without having him to submit the form as he did back in 90s.

Using the iframes

Well before the HTML5, people used hidden iframes to target the form to be uploaded from, the iframe is just another HTML document embedded in your main HTML document, that if even navigated to any other web page doesn’t trigger any navigation event in the main page. Which means that if the form is submitted through an iframe the main page the user stands on it never submitted. But he can still view the results and other associated data, such as form elements and the result window.

HTML5 and JavaScript

But these are also old now, JavaScript is strong enough to upload your files, and using HTML5 you can easily work you way with the validations of Files too. You can manage which file to upload and which one to reject. This option also minimizes the chances of error for any file that were triggered in the old methods and the user was informed of those errors after he uploaded all of the HTTP request data.

In JavaScript, we can shorten down the code for creating an Ajax request – An Ajax request is an asynchronous request to the server to get some resources from the server and display it in the web page without needing to reload the web page. This technology (Ajax) enables us, to get any data to the web server without having to use the POST requests and reload the web page for the new content, and similarly it also enables us to send any data to the server – such as files, images and other data – to the web server. This makes the uploading of the content an easy method.

jQuery code

In this blog post, I will be using jQuery – why? because I love jQuery, it is shorter in syntax and looks cool, but remember it is slower than pure JavaScript because it is just a library that runs over JavaScript but the difference is barely noticable – to send the Ajax requests to the server, along with the file data that we want to be uploaded.

The first stage is to create the HTML form that will be capturing any of the file that the user wants to upload to the server. For example, the following code would be an example of the HTML form that will accept the files from the user and contains a simple button from which he will upload the files – I know, button is old method, but in this method this button won’t perform the built-in function, it will be captured by JavaScript and the page will stay where it is all using the JavaScript watch the jQuery code for more on this section.

<form method="post" id="form" enctype="multipart/form-data">
  <input type="file" name="file" />
  <input type="submit" value="Upload" />
</form>

Above is the example for the form. Now once we will look into the jQuery code, we will be able to omit the enctype=”multipart/form-data” part too. Until then, this form is – as it stands – will accept a (single; multiple files are not allowed yet) file and the Upload button will be used to trigger the main function.

The following is the JavaScript (jQuery) code that will capture the event and send a request alongwith the file.

$(document).ready(function () {
   // On the document ready
   $('input[type=submit]').click(function () {
     // Before the request starts, show the 'Loading message...'
     $('.result').text('File is being uploaded...');
     event.preventDefault();
     // On the click even,
     var formData = new FormData($('#form')[0]);
       $.ajax({
           type: 'POST',
           processData: false,
           contentType: false,
           data: formData,
           success: function (data) {
              // The file was uploaded successfully...
              $('.result').text('File was uploaded.');
           },
           error: function (data) {
              // there was an error.
              $('.result').text('Whoops! There was an error in the request.');
           }
       });
    });
 });

.. in the above code, there is an element where the result is being rendered. That was like this,

<p class="result"></p>

.. in this element you will be showing the process that is currently going on.

  1. First of all – It will show a File is being uploaded… message in this paragraph.
  2. After the upload.
    If the file was uploaded, a success note will be shown otherwise an error message will be displayed to the user.

How will be button not submit the form by using a POST request? That is overridden by the code, in the second line inside the event handler. event.preventDefault(); in this code line, the default behaviour that will be triggered is overridden. Meaning that the page won’t be loaded again by a POST request, instead only that code will execute that we want – the Ajax code in the code block.

ASP.NET method to capture and make sure the request was having a File

You can use the following code of ASP.NET, that will make sure that the file is attached with the request, and then follow on to the Saving process and so on. For example this code,

files = Request.Files.Count;
if(files > 0) {
   // Files are sent!
   for (int i = 0; i < files; i++) {
      var file = Request.Files[i];
      // Got the image...
      string fileName = Path.GetFileName(file.FileName);
      // Save the file...
      file.SaveAs(Server.MapPath("~/" + fileName));
   }
}

Above code will work, for any image or any file type. There is no validation until now, you can attach your own validations depending on the Mime type or the size of the file that was attached the request.

Omitting the enctype

Oh well, I said that after the jQuery code I will explain how can you omit the enctype attribute – or if you even miss writing the enctype the result will be valid to upload the file – is that when you’re using the FormData object, to send the data, it make the form to behave as if the enctype of the form was set to the multipart/form-data (which is required to encode the files and tranfer them on HTTP). ‘

That is why, even if you miss this part and are using the FormData you will see that the images are being uploaded to the server.

Points of Interest

HTML5 and jQuery are widely used frameworks to upload the files using Ajax request to the web servers making it easier to control the file types to be uploaded, validating the maximum file size to be uploaded and some other particular validation can be handled easily on the client-side making it easier for the user to perform uploading tasks fastly.

FormData is an object that once used makes it easy to encode the files and other data as if the form’s enctype was set to the multipart/form-data. This is used (and is required) to upload files on the server through HTTP requests.

You can prevent any default method to be executed upon any element or control, using the JavaScript’s preventDefault() method.

HTML Forms and their data; Plus Variables

I will assume that you guys are having the tools downloaded. So lets start!

What you currently have is IIS8, WebMatrix3 and some other tools that would run your database, which were installed alongwith the WebMatrix installation.

Now lets continue.

First of all, try to remind yourself of the HTML markup, and the CSS and JS.

Note: We will be using jQuery more often as compared to JavaScript.

So lets continue!

First of all, lets start with a very basic concept.

Using a Form!

<form method="post">
   <input type="text" name="name" />
   <input type="text" name="age" />
   <input type="submit" value="Submit" />
</form>

Now lets try to understand the very basics of it.

This form uses a method=”post” which changes the method of HttpRequest of the current form to POST. Which means that your form values will be submitted safely and directly to the browser. Contrary to this, you might have also used method=”get”; please note that this is the default behaviour of the form too. If there is no method, then it is a GET request.

The very basic difference for a beginner would be; a GET request creates a URL for the parameters of the FORM, and then the Server uses those parameters and processes the Request. Contrary to this, POST will just send the request directly to the server, and not having the Browser of any other ClientAgent involved.

Now lets move to the next part; the input. This is used to let the user write some values in a field, which will be sent to the server then. You can have other type of inputs too, such as radio buttons, checkboxes, email input, even password.

Now, the last and the same type of element used is the input, but with the type attribute set to submit. Which means that this button will submits the current form.  This way, you will get your data submitted to the server within a few seconds. Well actually it depends on what kind of data to send too.

This was the part which was easy to code, now comes the real horror! No wait, don’t worry it will be easier as talking. Lets start.

Since you downloaded WebMatrix, you might have noticed some other softwares downloaded too, such as Web Pages 2 and some other MS technologies. Now its their time to jump in and save the data. How?

Since these are the server-side technologies, you will use these languages to save the data or do what ever you want to do with them. I am sure, you might have downloaded that StarterSite template or any other from the Template Gallery; donot download WordPress or Joomla! templates as we won’t discuss PHP here right now. You require an ASP.NET website.

So, in a new page called “NewPage.cshtml” create a form as demonstrated above. Once you load the page, you will be able to see the form there. Now what you might want to do is to write some of the server-side codes there too. To make sure the data sent to the server gets saved somewhere too, as the user won’t like to keep sending the data when you’re not even saving it.

So here is the code for too.

First you need to create a server-side block for the code to execute.

@{
   // all the codes will be written here..
}

This is the way, a server-side code gets started and an end, in ASP.NET. Now how to manage it.

Use this:

@{
  if(IsPost) { // remember that we have set method to post, 
               //so if method is post then this..now create variables
    var name = Request.Form["name"]; // request the name input from the form
    var age = Request.Form["age"]; // request the age input from form
    // do whatso ever here.. then close the block and done!
  }
}

This block needs to be on the top of the page, even before HTML tag. Since we won’t require it in the client side, so we won’t need to care where it is placed. But remember we need to place it above, so that when the page is being executed all the variables and the code are compiled and are available throughout the DOM. For example:

@{ 
   var something = newThing;
   var newThing = "Hello";
}

This is wrong, because the server will look for the variable something in the current document, but there won’t be anything, since the variable is being declared below. So this would cause an error. To minimize this, each variable should come below its creation such as:

@{ 
   var newThing = "Hellow";
   var something = newThing;
}

You can use as many of the variables you want, and you can name them on your choice. Think like they’re your kids.

You can learn more about saving the form data to a file, reading the file in a server-side, deleting and creating a file in the link below.

http://www.asp.net/web-pages/tutorials/files,-images,-and-media/working-with-files