Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Saturday, 23 November 2013

How to secure jQuery AJAX calls in PHP from hackers?

How to secure jQuery AJAX calls in PHP from hackers?

If you are making jQuery AJAX calls in your PHP website, please ensure that those jQuery AJAX calls are secure from website hackers. Your code should not be vulnerable to hackers. Below are some methods and steps which need to be taken to secure your jQuery AJAX calls to PHP files. I am writing this post because I had written a simple post "How to call PHP function from JavaScript function? Always use AJAX." without mentioning any security code. I got following comment on that post:

"Your code is very vulnerable. You're not filtering the $_POST variable at all. This opens yourself to HTML injection. A hacker could pwn your web site very quickly if you used this code. Careless examples like yours is exactly why so many web sites are hacked."

That's why this is my small attempt to make your jQuery AJAX calls secure. 

1. Use $_SERVER['HTTP_X_REQUESTED_WITH']: 

This is a basic check to see if the request is an Ajax request or not?

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&       strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
{
    //Request identified as ajax request
}

However you should never base your security on this check. It will eliminate direct accesses to the page if that is what you need.

2. Use $_SERVER['HTTP_REFERER']: 

if(@isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="http://yourdomain/ajaxurl")
{
 //Request identified as ajax request
}

But not all browsers set it. So don't properly rely on it but yes, to some extent it can secure your webpage.

Nobody can AJAX your site from other domain, but always can connect and drieclty send http request, for example by cURL.

JavaScript running on another domain cannot access any page on your domain because this is a violation of the Same-Origin Policy. The attacker would need to exploit an XSS vulnerability in order to pull this off. In short you don't need to worry about this specific attack, just the same old attacks that affect every web application.

3. Generate Access Tokens

$token = md5(rand(1000,9999)); //you can use any encryption
$_SESSION['token'] = $token; //store it as session variable

You can create some token in cookies, that will be also seen from jquery request, but that solution can also be hacked.

4. Always check $_POST variables in your PHP file whether those are set or not? Whether there is valid value in $_POST or not before executing the actual PHP code.

Basic code snippet for securing your jQuery AJAX calls in PHP

Step-1 : Generate Token System For All Web-Service:

Generating Token :

<?php
  session_start();
  $token = md5(rand(1000,9999)); //you can use any encryption
  $_SESSION['token'] = $token; //store it as session variable
?>

Step-2 : Use it while sending ajax call:

var form_data = 
{
  data: $("#data").val(), //your data being sent with ajax
  token:'<?php echo $token; ?>', //used token here.
  is_ajax: 1
};

$.ajax({
  type: "POST",
  url: 'yourajax_url_here',
  data: form_data,
  success: function(response)
  {
    //do further
  }
});

Step-3 : NOW, Let's secure ajax handler PHP file with,

session_start(); 
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') 
{
  //Request identified as ajax request

  if(@isset($_SERVER['HTTP_REFERER']) &&    $_SERVER['HTTP_REFERER']=="http://yourdomain/ajaxurl")
  {
   //HTTP_REFERER verification
    if($_POST['token'] == $_SESSION['token']) {
      //do your ajax task
      //don't forget to use sql injection prevention here.
    }
    else
   {
      header('Location: http://yourdomain.com');
    }
  }
  else 
  {
    header('Location: http://yourdomain.com');
  }
}
else 
{
  header('Location: http://yourdomain.com');
}

Monday, 21 October 2013

How to pause javascript setInterval method for sometime and restart again?

How to pause javascript setInterval method for sometime and restart again?

I was using javascript setInterval method to display different divs after a regular interval of time. In between, I fell into the requirement of pausing the javascript setInterval method for sometime, do some stuff and restart it again. So, I repeatedly used setInterval and clearInterval to acheive my functionality. 

I have 3 divs: div0 (green), div1 (yellow), div2 (red). All are overlapping each other. I am using setInterval to hide and show div1 and div2 after every second. if index = 4 or 6, I am showing red div else yellow div. 

My requirement is that, When index becomes 8, I want to pause the setInterval for 5 seconds and till then show div0 (green) and afterwards resume the loop of setInterval until clearInterval is called.

Below is the code snippet for pausing and restarting setInterval method which is self explanatory.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Sample Application</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
    var index=0;    
    var auto_refresh = 0;
    $(document).ready(function(){
    hideDiv();
    auto_refresh = setInterval(function(){myTimer()}, 1000);

    });

    function myTimer() 
    {
            index+=1;

            if(index == 4 || index==6)
            {
              showDiv2();
            }   

            else if (index == 8) 
            {
              clearInterval(auto_refresh);
              showDiv0();
              auto_refresh = setInterval(function(){myTimer()}, 5000);  //Now run after 5 seconds
            }

            else if (index > 12) 
            {
              clearInterval(auto_refresh);
            }       

            else
            {
              showDiv1();
            }

        }

    function hideDiv()
    {
      document.getElementById("div0").style.visibility="hidden";
      document.getElementById("div1").style.visibility="hidden";
      document.getElementById("div2").style.visibility="hidden";
    }

    function showDiv0()
    {
      document.getElementById("div0").style.visibility="visible";
      document.getElementById("div1").style.visibility="hidden";
      document.getElementById("div2").style.visibility="hidden";
    }

    function showDiv1()
    {
      document.getElementById("div1").style.visibility="visible";
      document.getElementById("div0").style.visibility="hidden";
      document.getElementById("div2").style.visibility="hidden";
      document.getElementById("div1").innerHTML=index;
    }

    function showDiv2()
    {
      document.getElementById("div2").style.visibility="visible";
      document.getElementById("div0").style.visibility="hidden";
      document.getElementById("div1").style.visibility="hidden";
      document.getElementById("div2").innerHTML=index;
    }

    </script>

  </head>
  <body>
    <div id="container" style="position:relative;">

<div id="div0"     style="background:green;height:200px;width:200px;margin:0;position:absolute">
Relaxing for 5 seconds
</div>
         
<div id="div1" style="background:yellow;height:200px;width:200px;margin:0;position:absolute">
This is div1
</div>

<div id="div2" 
style="background:red;height:200px;width:200px;margin:0;position:absolute">
This is div2</div>
</div>

</body>
</html>

Note: I had discussed this problem on stackoverflow and written the conclusion of the discussion here in this post.

Sunday, 20 October 2013

How to show / hide images randomly at regular intervals in javascript by shuffling the array?

How to show / hide images randomly at regular intervals in javascript by shuffling the array?

I had one requirement in one of my projects that I had an image which I had to show randomly in 4 places (div) in my webpage at regular intervals using javascript. I had asked this problem in stackoverflow. I got good help from a guy named "Hiral" there. With his/her help, I was able to implement this functionality. For implementing my functionality, I am shuffling an array and using javascript setInterval() and clearInterval() methods. Let me explain you my requirement and solution. Maybe you encounter similar requirement in future, then it might be helpful to you!

I have following 4 divs (bulb1, bulb2, bulb3, bulb4) and the image bulb.png in images folder of my project.

<div id="bulb1" class="lightbulb"><img src=".\images\bulb.png" /></div>
<div id="bulb2" class="lightbulb"><img src=".\images\bulb.png" /></div>
<div id="bulb3" class="lightbulb"><img src=".\images\bulb.png" /></div>
<div id="bulb4" class="lightbulb"><img src=".\images\bulb.png" /></div>

Initially, I will hide all these divs by calling my following function:

function hideBulbImages()
{
        document.getElementById('bulb1').style.visibility = "hidden";
        document.getElementById('bulb2').style.visibility = "hidden";
        document.getElementById('bulb3').style.visibility = "hidden";
        document.getElementById('bulb4').style.visibility = "hidden";
}

Now lets say I have an html button on the click of which I am calling below function showBulbImages. As I said I have 4 divs (places in html page) where I have to light the bulb randomly, so I am shuffling the array "myArray" in the below function so that array gets randomized by calling the function "shuffleArray". When array gets shuffled or randomized, I use javascript setInterval() method to turn on the visibility of bulbs randomly at regular intervals, 1 second in my case. When setInterval() method runs 4 times, I call clearInterval() to stop the show.

function showBulbImages()
    { 
        var blink_count = 0;
        var myArray = ['1', '2', '3', '4'];
        var randomArray = shuffleArray(myArray)
        var blink_the_bulbs = setInterval(function() {      
            var blinking_bulb = "bulb" + randomArray[blink_count];
            document.getElementById(blinking_bulb).style.visibility = "visible";
            blink_count+=1;
            if (blink_count > 3) 
            {
                 clearInterval(blink_the_bulbs);
            }
        }, 1000);
    }

    function shuffleArray(array) 
    {
        for (var i = array.length - 1; i > 0; i--) 
        {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
        return array;
    }

Friday, 18 October 2013

How to use setInterval and clearInterval jQuery methods in PHP?

How to use setInterval and clearInterval jQuery methods in PHP?

I will explain usage of setInterval and clearInterval jQuery methods with the help of simple example in PHP. Suppose there is a PHP array in which there are 3 elements. I want to display all of them one by one at regular intervals and stop when all the three array elements have been displayed. I will use setInterval and clearInterval jQuery methods here to implement it.

Here is my index.php file

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var count = 0;
$(document).ready(function(){
var auto_refresh = setInterval(function (){
    $('#mydiv').load('myphpfile.php', {count: count}, function () {
        count = count + 1;
        //after three attempts it won't call php file.
        if (count > 2) {
            clearInterval(auto_refresh);
        }
    }).fadeIn("slow");
    }, 1000); 
});
</script>
</head>
<body>
<div id="mydiv"> </div>
</body>
</html>

Here is my myphpfile.php file

<?php
$questions=array(
                 "Array Item 0",
                 "Array Item 1",
                 "Array Item 2");

if (isset($_REQUEST["count"])) 
{
    echo $questions[intval($_REQUEST["count"])];
}
?>

Thursday, 17 October 2013

How to generate Random Numbers at Regular Intervals in PHP?

How to generate Random Numbers at Regular Intervals in PHP? 

Following is the simple PHP tutorial to demonstrate how to generate random numbers at regular intervals in PHP? I will use jquery setInterval() method for calling PHP file (which generates random numbers) at regular intervals say after every second in my example. I will use PHP rand() function to generate random numbers in PHP. I am using google CDN for jquery libraray. So here is the simple example in PHP to generate random numbers at regular intervals.

index.php file

<!DOCTYPE html>
<html lang="en">

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

<script type="text/javascript">
$(document).ready(function(){
var auto_refresh_random_numbers = setInterval(
function ()
{
$('#load_random_numbers').load('generate_random_numbers.php').fadeIn("slow");
}, 1000); // refresh random numbers after every 1000 milliseconds
});
</script>

</head>

<body>
<div id="load_random_numbers"> </div>
</body>

</html>

generate_random_numbers.php file

<?php
echo rand();
?>

So, that's all. Above PHP code snippet is very easy to understand by everyone. So, I don't think there is need of any explanation.

Thursday, 31 January 2013

jQuery Basic Interview Objective Questions and Answers (Part 1)

jQuery Basic Interview Objective Questions and Answers (Part 1)

Here is a small list of 14 jQuery basic interview questions and answers which a web designer and developer must know who is going for technical interview of jQuery, Javascript and AJAX (UI: User Interface). Some of these jQuery interview questions are objective and some are subjective. These jQuery interview questions and answers should be on finger tips of each web designer and developer. Many basic jQuery interview questions are related to CDN (Content Delivery Network) like Google CDN, Microsoft CDN and EdgeCast CDN and some are based on jQuery selectors. Lets have a look at the following list of basic jQuery interview questions and answers.

1. Is jQuery a library for client scripting or server scripting?

jQuery is client scripting library.

2. Is jQuery a W3C standard?

jQuery is not a W3C standard.

3. What are jQuery Selectors?

Selectors are used in jQuery to find out DOM elements. Selectors can find the elements via ID, CSS, Element name and hierarchical position of the element.

4. Does the jQuery html() method work for both HTML and XML documents?

jQuery html() only works for HTML.

5. Which sign does jQuery use as a shortcut for jQuery?

$(dollar) sign.

6. What does $("div") will select?

It will select all the div element in the page.

7. What does $("div.parent") will select?

All the div element with parent class.

8. What is the name of jQuery method used for an asynchronous HTTP request?

jQuery.ajax()

9. What is CDN and what are the advantage of loading jQuery framework from CDN?

Always load your jQuery framework from Google, Microsoft or jQuery CDN(Content Delivery Network). As it provides several advantages.

1. You always use the latest jQuery framework.
2. It reduces the load from your server.
3. It saves bandwidth. jQuery framework will load faster from these CDN.
4. The most important benefit is it will be cached, if the user has visited any site which is using jQuery framework from any of these CDN.

10. Write down the code to load jQuery Framework from Google CDN.

</script>

11. Write down the code to load jQuery framework from Microsoft CDN.

</script>

12. Write down the code to load jQuery framework from jQuery website (EdgeCast CDN).

<script  type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>

13. How do you load jquery locally when CDN fails?

Below given jQuery code checks whether jQuery is loaded from Google CDN or not, if not then it references the jQuery.js file from your folder. 

</script>

<script type="text/javascript">
if (typeof jQuery == 'undefined')
{
  document.write(unescape("%3Cscript src='Scripts/jquery.1.5.1.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>

It first loads the jQuery from Google CDN and then check the jQuery object. If jQuery is not loaded successfully then it will reference the jQuery.js file from hard drive location. In this example, the jQuery.js is loaded from Scripts folder.

14. What is jQuery.noConflict?

jQuery is great library written on top of Java Script and its popularity is increasing day by day.The reason of popularity of jQuery is the plenty of useful, simple and easy to use plugins. But while using jQuery plugins, sometimes we include other libraries like prototype, mootools, YUI etc. The problem comes when one or more other libraries are used with jQuery as they also use $() as their global function and to define variables. This situation is creates conflict as $() is used by jQuery and other library as their global function. To overcome from such situations, jQuery has introduced jQuery.noConflict().

<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
     jQuery.noConflict();
     // Use jQuery via jQuery(...)
     jQuery(document).ready(function(){
       jQuery("div").hide();
     }); 
     // Use Prototype with $(...), etc.
     $('someid').hide();
</script>

When .noConflict() is called then jQuery returns $() to its previous owner and you will need to use jQuery() instead of shorthand $() function. In this case, "jQuery" will be used in rest of the code. You won't be able to take advantage of shorthand.

<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
     var $j = jQuery.noConflict();
     // Use jQuery via jQuery(...)
     $j(document).ready(function(){
       $j("div").hide();
     }); 
     // Use Prototype with $(...), etc.
     $('someid').hide();
</script>

Why to use Google CDN for jQuery libraries instead of hosting them locally?

Why to use Google CDN for jQuery libraries instead of hosting them locally?

I have seen a lot of websites which call jQuery libraries locally by downloading them to their hard disk instead of using Google CDN (Content Delivery Network) like this:

<script type="text/javascript" src="/js/jQuery.min.js"></script>

This approach has a lot of disadvantages. I will suggest you to use Google CDN (Content Delivery Network) to call jQuery libraries instead of downloading and then calling them. Right approach of calling jQuery libraries from Google CDN is:

</script>

Usind Google CDN provides a lot of advantages like:

1. Decreased Latency

A CDN — short for Content Delivery Network — distributes your static content across servers in various, diverse physical locations. When a user’s browser resolves the URL for these files, their download will automatically target the closest available server in the network.

In the case of Google’s AJAX Libraries CDN, what this means is that any users not physically near your server will be able to download jQuery faster than if you force them to download it from your arbitrarily located server.

There are a handful of CDN services comparable to Google’s, but it’s hard to beat the price of free! This benefit alone could decide the issue, but there’s even more.
 
2. Increased Parallelism

To avoid needlessly overloading servers, browsers limit the number of connections that can be made simultaneously. Depending on which browser, this limit may be as low as two connections per hostname.

Using the Google AJAX Libraries CDN eliminates one request to your site, allowing more of your local content to downloaded in parallel. It doesn’t make a gigantic difference for users with a six concurrent connection browser, but for those still running a browser that only allows two, the difference is noticeable.

3. Better Caching

Potentially the greatest benefit of using the Google AJAX Libraries CDN is that your users may not need to download jQuery at all.

No matter how well optimized your site is, if you’re hosting jQuery locally then your users must download it at least once. Each of your users probably already has dozens of identical copies of jQuery in their browser’s cache, but those copies of jQuery are ignored when they visit your site.
 
However, when a browser sees references to CDN-hosted copies of jQuery, it understands that all of those references do refer to the exact same file. With all of these CDN references point to exactly the same URLs, the browser can trust that those files truly are identical and won’t waste time re-requesting the file if it’s already cached. Thus, the browser is able to use a single copy that’s cached on-disk, regardless of which site the CDN references appear on.

This creates a potent “cross-site caching” effect which all sites using the CDN benefit from. Since Google’s CDN serves the file with headers that attempt to cache the file for up to one year, this effect truly has amazing potential. With many thousands of the most trafficked sites on the Internet already using the Google CDN to serve jQuery, it’s quite possible that many of your users will never make a single HTTP request for jQuery when they visit sites using the CDN.

Even if someone visits hundreds of sites using the same Google hosted version of jQuery, they will only need download it once!

Friday, 25 January 2013

jQuery Tutorials: Tips and Tricks for Web Developers

jQuery Tutorials: Tips and Tricks for Web Developers

jQuery has made web designing and development very easy. In this jQuery tutorial, some basic points about jQuery are listed like shorthand for jQuery and importance of CDN (Content Delivery Network). We have also covered some cool jQuery tips and tricks which are commonly used while web designing and development like how to disable right click on web browser in a single line of jQuery script, how to get mouse position using jQuery script, how to find which mouse button was clicked and how to efficiently use jQuery selectors? Every web designer and developer should know these basic tips and tricks of jQuery. These are very easy to learn and grasp and also time saving which reduces human efforts.

1. Use shorthand for $(document).ready()

We can write jQuery code like this:

$(document).ready(function()
{
  //Your jQuery code goes here.
})

But there is a shorthand available for above code. This can be rewritten as

$(function ()
{
   //Your jQuery code goes here.
});

2. Always load jQuery framework from Google, Microsoft or jQuery CDN(Content Delivery Network).

CDN provides several advantages:

1. You always use the latest jQuery framework.
2. It reduces the load from your server.
3. It saves bandwidth. jQuery framework will load faster from these CDN.
4. The most important benefit is, it will be cached if the user has visited any site which is using jQuery framework from any of these CDN.

Code to load jQuery Framework from Google CDN

<script  type="text/javascript"
    src="
http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>

Code to load jQuery Framework from Microsoft CDN

<script  type="text/javascript"
    src="
http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</script>

Code to load jQuery Framework from jQuery Site(EdgeCast CDN)<script  type="text/javascript"
    src="
http://code.jquery.com/jquery-1.4.2.min.js">
</script>

3. How to disable right click using jQuery?

You can find many java script code snippets to disable right click. But jQuery makes our life easy. Below jQuery code disables the right click of mouse.

Method 1:

$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
    });
});

Method 2:

$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        e.preventDefault();
    });
});

4. How to get mouse cursor position using jQuery?

$(document).ready(function(){
  $(document).mousemove(function(e){
     $('#spnCursor').html("X Axis : " + e.pageX + " Y Axis : " + e.pageY);
  });
});

When the DOM is ready, we listen for mousemove event. Whenever user moves the mouse then this event gets called and we bind the pageX and pageY property to the span element.

5. How to find which mouse button is clicked using jQuery?

If you need to determine which mouse button (Left, Middle or Right) was clicked. jQuery provides mousedown() event, using which we can check which mouse button is clicked. For key or button events, event attribute indicates the specific button or key that was pressed. event.which will give 1, 2 or 3 for left, middle and right mouse buttons respectively. The advantage of using event.which is that it eliminates cross browser compatibility.

$(document).ready(function() {
$('#btnClick').mousedown(function(event){
    switch (event.which) {
        case 1:
            alert('Left mouse button pressed');
            break;
        case 2:
            alert('Middle mouse button pressed');
            break;
        case 3:
            alert('Right mouse button pressed');
            break;
        default:
           break;
    }
});
});

6. How to use jQuery selectors efficiently?

It is pretty important to understand how to write efficient element selection statement. One has to be very careful while jquery selector statement. Below are some tips on how to use your jQuery selectors efficiently.

A. Always try to use ID as selector

You can use ID as selector in jQuery. See below jQuery code.

$("#elmID");

When IDs are used as selector then jQuery internally makes a call to getElementById() method of Java script which directly maps to the element.

When Classes are used as selector then jQuery has to do DOM traversal.So when DOM traversal is performed via jQuery takes more time to select elements. In terms of speed and performance, it is best practice to use IDs as selector.

B. Use class selector with tags

You can use CSS classes as selector. For example, to select elements with "myCSSClass" following jQuery code can be used.

$(".myCSSClass");

As said earlier, when classes are used DOM traversal happens. But there could be a situation where you need to use classes as selector. For better performance, you can use tag name with the class name. See below

$("div.myCSSClass");

Above jQuery code, restricts the search element specific to DIV elements only.

C. Keep your selector simple, don't make it complex

Avoid complex selectors. You should use make your selectors simple, unless required.
$("body .main p#myID em");

Instead of using such a complex selector, we can simplify it. See below:

$("p#myID em");

D. Don't use your selector repeatedly

See below jQuery code. The selectors are used thrice for 3 different operation.

$("#myID").css("color", "red");
$("#myID").css("font", "Arial");
$("#myID").text("Error occurred!");

The problem with above code is, jQuery has to traverse 3 times as there are 3 different statements.But this can be combined into a single statement.

$("p").css({ "color": "red", "font": "Arial"}).text("Error occurred!");
 
E. Know how your selectors are executed

Do you know how the selectors are executed? Your last selectors is always executed first. For example, in below jQuery code, jQuery will first find all the elements with class ".myCssClass" and after that it will reject all the other elements which are not in "p#elmID".

$("p#elmID .myCssClass");

Saturday, 15 December 2012

Multiple File Upload Progress Bar Script using PHP, HTML5, jQuery and AJAX Plugins

Multiple File Upload Progress Bar Script using PHP, HTML5, jQuery and AJAX Plugins

Multiple File Upload With Progress Bar functionality is very common in online websites. Creating a multiple file upload progress bar script is very easy by using PHP, AJAX and jQuery. I will use AJAX Library from Github to create a script for multiple file upload and progress bar. This tutorial on multiple file upload will demonstrate step by step scripting for multiple file upload using PHP, jQuery and AJAX Plugin.

First, we will create a multiple file upload button using HTML and then we will put some CSS on this multiple file upload button to design it and make it more interactive. After creating multiple file upload button, we will add PHP script which will upload the multiple files and show the progress bar. Last but not the least, we will add AJAX Plugin for multiple file upload from Github in our working folder and then use that multiple file upload plugin in our javascript code. I have also done some error handling in my javascript code like a user can only multiple upload PNG, GIF and JPG files. You can impose extra checks as per your requirement. I am also showing the progress bar while multiple files are being uploaded.

Step 1: Create Upload Button using HTML

<div id="upload" >Upload File</div> 
<span id="status" ></span> 
<ul id="files"></ul> 

Step 2: Design Upload Button using CSS

#upload
{ 
    margin:30px 200px; padding:15px; 
    font-weight:bold; font-size:1.3em; 
    font-family:Arial, Helvetica, sans-serif; 
    text-align:center; 
    background:#f2f2f2; 
    color:#3366cc; 
    border:1px solid #ccc; 
    width:150px; 
    cursor:pointer !important; 
    -moz-border-radius:5px; -webkit-border-radius:5px; 
}

Step 3: Add PHP Multiple File Upload Script

Below is the PHP script for multiple file upload. This PHP script will show 'Success' message when all the files are uploaded successfully. If there is any error while uploading multiple files, the PHP script will report an error.

<?php 
$uploaddir = './uploads/';  
$file = $uploaddir . basename($_FILES['uploadfile']['name']);  
  
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file))
{  
  echo "success";  
}
else
{ 
    echo "error"; 
} 
?> 

Step 4: Add jQuery and Javascript to your code

First of all, you have to include jQuery Multiple File Uploader Plugin from GitHub. Here is the link: https://github.com/valums/file-uploader

$(function(){ 
    var btnUpload=$('#upload'); 
    var status=$('#status'); 
    new AjaxUpload(btnUpload, { 
        action: 'upload-file.php', 
        //Name of the file input box 
        name: 'uploadfile', 
        onSubmit: function(file, ext){ 
            if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){  
                  // check for valid file extension  
                status.text('Only JPG, PNG or GIF files are allowed'); 
                return false; 
            } 
            status.text('Uploading...'); 
        }, 
        onComplete: function(file, response){ 
            //On completion clear the status 
            status.text(''); 
            //Add uploaded file to list 
            if(response==="success"){ 
                $('<li></li>').appendTo('#files').html('<img src="./uploads/'+file+'" alt="" /><br />'+file).addClass('success'); 
            } else{ 
                $('<li></li>').appendTo('#files').text(file).addClass('error'); 
            } 
        } 
    }); 
}); 

Multiple File Upload Progress Bar Script Explanation:

To use the AJAX Upload library we need to initialize the AjaxUpload object and provide it with parameters. The first parameter is the id of the button element on which the user will click and second is the server side script that’ll handle file upload. The second parameter can accept an array of various options to give you more control over the process.

And that’s exactly what I have done:

1. The action field is the path to server side script,

2. name is the name of file input box(hidden) which will be used for upload. If you change this value, make sure to change the server side script corresspondinly.

3. onSubmit lets you perform some function before the file is uploaded e.g. you can check the file extension like i’ve done above or show a status message.

4. onComplete lets you perform some action after the upload is complete e.g. I’ve shown the uploaded image to the user.

And if you want to limit the number of files that a user can upload at a time, simply use this.disable() within onSubmit or onComplete to disable the upload button after checking for some condition.
 
Note: The file upload using AJAX is not true ajax as it uses hidden iframe to upload the form data but his whole process is transparent by using the AJAX Upload library and gives a feel of AJAXified file upload.