Tag Archives: jquery

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.

Advertisements

Where to start from?

Many new developers ask the question to themself and to other fellow developers. The question is simple, for me and for old developers but, it is not easy for the new ones. Question is, ‘Where to start the journey?‘. I had the very same question when I started the journey of development.

I first became a Web Developer, I learnt HTML basics and CSS basics at w3schools.com, but I won’t recommend that website to others. They do have an editor and show some of the code. But they’re not good at explaining the code. They just explain that this code would do this. But not, why this code would do this.

I would recommend using Mozilla Developer Network, if you need an editor (currently, Mozilla doesn’t support this feature. If, when you’re visiting this page, Mozilla adds this, comment please) to test your HTML knowledge, you should go with any online text editor like jsfiddle.net. Otherwise, you can even use your very own NotePad to do this. Here is the process for that

  1. Open the Notepad in the Windows, or any other OS. Just make sure you can write the text in it.
  2. Write the HTML codes, make sure, you’re having the HTML elements properly opened and closed.
  3. Saving the file. Here is the main part, just write the file name and add the format of html or htm, like this
    fileName.html

This would create a Browser file for you. Once you click on it, browser would load the file and will show the HTML content to you.

Pretty easy right?

Once you’re good to go with the HTML thing. Try creating something. Like a personal landing page, using all the HTML elements and other stuff like that. After this, you should go for a server-side language and Install the Softwares required and all that kinda thing. I think I had that covered in the other page.

Printing the page

I had to go through the printing process as I got a new project from my cousin. On my way, I never ever did such a job which involved printers or hard copy format for the documents. Now that I had the job for that, I started looking up for some resources. I did know that I can use CTRL + P key command to print. But, how to integrate all that inside the HTML document, I was making up some assumptions. And this was what I got.

First thing was to print the page. So for that you can create a button element inside your HTML document and handle it using jQuery for the print event. Here is the code for that:

<button>Print</button>

/* Script part */
$('button').click(function () {
  window.print();
}

Now the browser would show a simple window, where you would get more options to control the printed version of the page. You can either set them there, or you can use the code to control the page layout even more better. What you would try here is CSS3’s Media Query.

Here is the example, lets assume we’re having a div inside the body element. Which is having the id of printable and all the other body is given the id of non-printable. Now in the CSS you were taught for the usage of Media Query.

You can use this code:

@media print {
  #printable {
    display: block;
  }
  #non-printable {
    display: none;
  }
}

That was enough here. Now you can use this code to view only the printable part of the page. Which would be helpfull to save the page and to get the desired output.

Some other tips you might need to use:

  1. Always use CSS3 media query to stylize the printable version.
  2. Always keep the width larger so that height of the page is less. Saves the page!
  3. Always keep the note on the page by clicking the button or by Print command. To keep a note on the printed version too.
  4. Keep the font-size short and easy to read.
  5. Use short sentences and good punctuations. It makes the document better to be read. Less words save the space
  6. Always remember to remove the margins and paddings from the body element. Printer would automatically add the margin and paddings to the page which would be enough.

Windows app development

Well, since the upgrade of Windows 8, developers can now develop apps in HTML and CSS. Windows 8.1 has some other built-in bug fixes too. But this feature came up by the upgrade of OS from Win 7 to Win 8.

Now, we can create a simple and easy HTML software for Windows API. We can stylize it using CSS, and we can work on the events using JavaScript, man please no more JavaScript talk, I am sick of it. jQuery would be used here more oftenly, but still we would need to stick to pure (or native) JavaScript in some places where we would be handling the OS based messages.

So, let us get our selves warmed up for Windows Programming too. It’s just been made easy for us!

For more go to: http://msdn.microsoft.com/en-us/windows/apps/br229512

Some basics of jQuery

Well, I guess our website is now a good to go for uploading and deleting the files from the server. But that doesn’t look that much cool, is it?

Adding some pro features

So lets start adding some professional features to it! For example, lets try to add some names or some more content to the page or lets just add some cool styles to the page like showing the form or hiding the form. Should we? Okay then,

First Step:

First step we will do will be to go to this site: http://jquery.com/ and download the latest version of jQuery or even download the recommened one. Don’t like to read and do all that stuff? Its ok! Try to add this link in the head section of your website

<script href="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

But for those of you, who don’t like to add unknown stuff to their websites, you can download the file attached below in this post 🙂 You will read alot there, but please note that this method isn’t preferred. First or second would be great.

Lets begin the coding

Ok, so I guess you are now having your website connected to the powerfull JavaScript Library jQuery. Try to understand, that jQuery itself is a JS. It is not something else, it in the code behind the scenes makes a use of the pure js and lets you easily handle the events on the browser.

Understanding the methods

Now lets start understand how we can handle the events on an elements using jQuery.

In basic js, you wrote the stuff as

<element onclick="functionname"></element>
// such as
<button onclick="submitform"></button>

Now to handle the event you did something like

<script>
  function submitform() {
    // remember functions are methods so you must use
    // (). You can pass parameters through this too. 
    // and here you submitted the form or validated it 
  }
</script>

But jQuery makes it simpler and easier. How? Look for yourself

<script>
   // now lets use the input of text as the name
   // and the submit as the button to execute the change
   $('#submit').click(function () {
     var name = $('#name').val(); // val is a method; thus ()
     alert(name); // alert the name for the user..
   });
</script>

<!-- body elements are as under -->

<input type="text" name="name" id="name" />
<input type="submit" value="Submit" id="submit" />

The above code will first take the user’s input for the name and then it will show the name as an alert when the user will click submit. You can see the code working by the usage of the id (#).

Now lets understand what other stuff jQuery can do for us.

Hiding and showing the content

If we want to hide the content, or show a content sometime when we want it to be visible to the user such as a popup; customized one. Then we can make a use of jQuery and toggle it using

<button></button>

// jQuery for this will be
$('button').hide();
$('button').show();
$('button').toggle();

Now, you might want to ask what is toggle? Toggle means if the element is hidden it will show it, if it is visible it will hide it! Its a round-off for the hide/show methods. You can also use the speed for the process in milliseconds. Forexample if you write 1000 in the paranthesis then the process will take 1 second and will hide or show in a perfect manner for the user to understand that something is coming up for me to fill in or view.

Changing CSS properties for elements

There are some other uses of jQuery too, such as changing the CSS for the current element. We can do that using

$('element').css({
  // write the properties here such as
  "width": "100px",
  "height": "50px"
});

And so on. jQuery is an endless library of JS. You will find each and everything and will be able to edit and customize the page effects using just jQuery.

Good luck.