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 Ajax form (HTML and PHP)
In this tutorial we use a simple 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 a 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.
Related posts
- jQuery Contact form for your website
- Ajax requests using jQuery and PHP
- Upload in modal window and pass values with jQuery
Comments
Trackback URL for this post: http://www.web-development-blog.com/archives/jquery-form-plugin-and-php-file-uploads/trackback/
Sorry, the comment form is closed at this time.








This is exactly what I was looking for; clear, concise, and simple. Thx!