jQuery form plugin and PHP file uploads

The past months I used the jQuery form plugin in several projects. Most forms were contact or feedback forms and some of them did a file upload as well. In a previous tutorial we explained how-to create a sign-up form for MailChimp. This sign-up form is a great example to use the jQuery form plugin as well.

What do you get in this tutorial

  • First we investigate the form plugin a little bit and explain some interesting features
  • With this knowledge in mind we will showcase some of the plugin’s functions
  • Finally we provide examples on how-to use the form plugin for simple forms with different response methods

Example files for the web form (HTML and PHP)

In this tutorial we use a simple contact form (example.php) that will post an email address and is able to upload one file. Below this form there is a container called #output, this DIV element is used to show the response from the process.php file.

<div id="container">
	<form action="process.php" method="post" id="my-form" enctype="multipart/form-data">
		<p>E-mail<br />
		<input type="text" name="email" id="email" /></p>
		<p>File<br />
		<input type="file" name="upload" id="upload" /></p>
		<p><input type="submit" value="Submit" /></p>
	</form>
</div>
<div id="output"></div> 

Our PHP example (process.php) has only two main functions; validate the email address entry and test/process the file upload. To make this example more clear, we show only some information extracted from the uploaded file. If you need a full featured upload function, you should try this PHP upload class.

if (isset($_POST['email'])) {	
	if (preg_match('(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,})', $_POST['email'])) {
		$msg = 'E-mail address is valid';
	} else {
		$msg = 'Invalid email address';
	}
	if ($_FILES['upload']['error'] > 0) {
  		$upl = '<br />Error: ' . $_FILES['upload']['error'] . '<br />';
    } else {
		$upl = '<br />Upload: ' . $_FILES['upload']['name'] . '<br />';
		$upl .= 'Type: ' . $_FILES['upload']['type'] . '<br />';
		$upl .= 'Size: ' . ($_FILES['upload']['size'] / 1024) . ' Kb<br />';
		$upl .= 'Stored in: ' . $_FILES['upload']['tmp_name'];
  	}
	echo $msg.$upl; // output the result
} else {
	die('Invalid entry!');
}

Using the form plugin is easy!

To process our form the Ajax style with the jQuery plugin, we need only some simple JavaScript code. Add the following code into the header section from your example.php file:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() { 
    var options = { target: '#output' }; 
    $('#my-form').submit(function() { 
        $(this).ajaxSubmit(options); 
        return false; 
    });
}); 
</script>

Running this script will process your form without to reload the page in your browser and as the result you get some information below your form. Before we change our example to have a more advanced web form, we explain the most important options and features for the jQuery form plugin.

ajaxForm and ajaxSubmit Options

The plugin has two methods to process an Ajax contact form, we use for this tutorial only the submit type. For the simple example above we used already the option named target, you need this option if you don’t use the success handler option and if you use the default data type. If you like to do some client side form validation the option beforeSubmit should be used. Both options success and beforeSubmit are callback functions, create custom functions for custom functionality. There are several supported data types for the response: XML, JSON or Script. If you leave the option dataType empty the response is just HTTP data. There are more options, check the Options tab from the plugin resource site.

Client side form validations

The option beforeSubmit makes it possible to create a custom function to validate our form before the data is submitted to the process.php script. Using the following function we test if the field email if one is not empty.

function showRequest(formData, jqForm, options) { 
	var form = jqForm[0];
	// or use 
	// if (!$('input[@name=email]').fieldValue()) { 
	if (!form.email.value) { 
		$('#output').html('Email address is empty!'); 
		return false; 
	} else {	    		
		return true;
	}
} 

We use the plugin’s native array jqForm to identify the email field. As an alternative it’s possible to access the field via the function fieldValue. Next we need to enable the option beforeSubmit before the function call:

$(document).ready(function() { 
    var options = { target: '#output', beforeSubmit: showRequest }; 
    $('#my-form').submit(function() { 
        $(this).ajaxSubmit(options); 
        return false; 
    });
});

Using our example now, we get an error message if we left the email field empty, note this happens without a request to the server!

Advanced response handling

In our last example we want to change the way how the response will show up in our small application. After the form is submitted we want to remove the form and show some alternative header plus the data we get from the server. We split the data in two parts: the message and the file information from the file we have uploaded. First we change the process.php file a little bit, replace code echo $msg.$upl; with the following code:

echo '
<xml>
	<someText>'.$msg.'</someText>
	<uploadInfo>'.$upl.'</uploadInfo>
</xml>';

We create here XML nodes to hold the two strings, which we will access later from the custom response callback function.

function showResponse(responseText, statusText)  { 
	if (statusText == 'success') {
		$('#container').html('<h3>Some title</h3>'); 
		$('#output').html('<p>' + $('someText', responseText).text()  + '</p><div>' + $('uploadInfo', responseText).html() + '</div>'); 
	} else {
		alert('status: ' + statusText + '\n\nSomething is wrong here');
	}
} 

We added also a test for the statusText and some title header element. The header is a replacement for the form, to make it more clear when the form is submitted. The message and the info takes place in two different HTML elements.

Now we have a a simple Ajax upload form with form validation (client and server side), where the server response is placed in detailed HTML elements. Based on our example it’s possible to make the small application much bigger with more functions on the client side and the server side. I hope this tutorial has helped to understand how-to create an jQuery/Ajax form powered by the jQuery Form Plugin. If you have questions or if you like to show-case your own forms, of course based on this tutorial or similar examples, please feel free to post your message below. Please don’t spam, we moderate all comment submissions.

Published in: jQuery Code · PHP Scripts

12 Comments

  1. If I just want to catch the server message in String type, how to set the dataType value?
    server: upload.php

    client: index.html

    js:
    $(“#myform”).ajaxForm({
    //dataType: “string”,
    success:function(data){
    alert(data);//alert some html code, I just need the string
    }
    });

    1. Hi Tarak,
      Great that you like my tutorial.
      Do you need a progress bar that shows the real upload progress or just a simple animation?

  2. I am having serious problem with ajaxform() and ajaxsubmit. I have followed the due processes of creating all the codes but doesn’t trigger at all. I have no idea of where the problem might lie. I use both jquery library of 1.4.4 and 1.6.5 and still doesn’t trigger form submission

    1. Hi,
      I remember me that I had this kind of problems too. I think I used the error console In Firefox or Chrome to locate the problem. The jquery form plugin is great because your form will work even if JavaScript is disabled.

  3. Thanks for the great tutorial. I’m trying to implement the Form Plugin but I get a “too much recursion” error when I try to submit a form. I’ve looked at your code up and down and am sure that my code matches perfectly- so I’m not really sure what is causing the recursion. Any idea? Thanks.

  4. I am trying to implement jquery form plugin and I was curious with the below:

    What if the server does not respond at all? Are there additional options (ajax functions) that I could bind in addition to target, beforeSubmit and success? I could not find this in the example.

    1. Hi Naveen,
      check my comments below…

      What if the server does not respond at all?

      I’m not sure the tutorial is a little bit aged :) Is there a timeout setting? If not I guess there would happen nothing.

      Are there additional options (ajax functions) that I could bind in addition to target, beforeSubmit and success?

      Sure you can use any jQuery/JS code inside the option.

      I could not find this in the example.

      Right that’s the purpose for this PHP/jQuery tutorial. It’s an example about how-to use a 3rd party jQuery plugin. Especially for your first question, the documentation from the plugin author might help.

Comments are closed.