Upload Form using Ajax Jquery

Upload Form using Ajax Jquery

This post explains how to upload a form using Ajax, Jquery and PHP.

JQuery provides a library for this purpose and ajaxForm is method for this.

Submitting a form with AJAX doesn’t get any easier than this!

 

Download Link       Demo Link

 

Sample database design for table name contact.

This table contains id (primary key), name, document, message and inserted_on

CREATE TABLE IF NOT EXISTS `contact` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(100) NOT NULL,
 `document` varchar(100) NOT NULL,
 `message` text NOT NULL,
 `inserted_on` date NOT NULL,
 PRIMARY KEY (`id`)
 )

index.php

Contains simple HTML.

<form method="post" action="submitForm.php" id="frmContact"
name="frmContact" enctype="multipart/form-data">

The enctype attribute specifies how the form-data should be
encoded when submitting it to the server and multipart/form-data
means  no characters are encoded. This value is required when
you are using forms that have a file upload control.
 <span id="responseMessage"></span><br/>

 It is used for display the response message from server.
 <fieldset class="formClass" id="formClass">

 <p>
 <label>Name: </label>
 <input type="text" name="name">
 </p>

 <p>
 <label>Document: </label>
 <input type="file" name="updDocument"><br/><br/>
 <span class="docFormate">Only JPG,PNG and DOC allowed with less
than 2MB size.</span>
 </p>

 <p>
 <label>Message: </label>
 <textarea name="message"></textarea>
 </p>

 <p>
 <span id="submitBtn">
 <input type="submit" name="submitForm" value="Submit"
class="button marL114" onclick="return validForm()">
 <input type="reset" name="reset" value="Reset" class="button">
</span>
 <span id="flashShow"></span>

It is used for display the loading image.
 </p>
 </fieldset>
 </form>

Java Script Section

Contains the most important part of this tutorial.

jquery.form.js is jquery library. If the server response is other than done, than simply show the response message and if server response is done than just hide the form or reset the form and show success message.

<script type="text/javascript" src="js/jquery-1.4.1.min.js">
</script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript">
function validForm(){
 $("#submitBtn").hide();   // Hide submit and reset button
 $("#flashShow").show();   // Show loading image
 $("#flashShow").html('<img src="image/loading.gif"
class="marL114" border="0" />');
 var options ={success: function(data)
 {
 $("#flashShow").hide();  // Hide loading image
 $("#submitBtn").show();  // Again show buttons
 if(data=='done'){        // If server response is done
 $("#formClass").hide(); // If you dont wana hide the form than
only reset using jquery
 $("#responseMessage").html('Thank you for submitting your
contact information<br/>');
 }else{
 $("#responseMessage").html(data);
 }
 return false;
 }};
 $("#frmContact").ajaxForm(options).submit();
}
</script>

submitForm.php

Contains PHP code with name, message and document validation scripts and if all the condition full fill, upload document into upload_doc folder with document name rename into timestamp.

$response=array();
if(!empty($_POST['name'])){
$name=mysql_real_escape_string($_POST['name']);
}else{
 $response[] = "Please enter your name";
}

If Name is empty than put error message in response array and if
it is not empty than Escapes special characters from name using
function mysql_real_escape_string and put in variable.
if(!empty($_POST['message'])){
$message=mysql_real_escape_string($_POST['message']);
}else{
 $response[] = "Please enter your message";
}

If Message is empty than put error message in response array and
if it is not empty than Escapes special characters from message
using function mysql_real_escape_string and put in variable.
if (!empty($_FILES['updDocument']['name'])) {

$valid_document_formats = array("jpg", "png", "doc");
// Only JPG,PNG and DOC Document formate allowed in this script

$valid_document_size=2097152;
// 2MB Size allowed for document
$documentName = $_FILES['updDocument']['name'];
// Actual Document Name

$documentSize = $_FILES['updDocument']['size'];
// Actual Document Size
list($txt, $ext) = explode(".", $documentName);
// Get Actual Document Formate

if (in_array($ext, $valid_document_formats)) {
// Check Document Formate
if ($documentSize < $valid_document_size) {
// Check Document Size

$actual_document_name = time() . "." . $ext;
// Document New Name

$tmpDoc = $_FILES['updDocument']['tmp_name'];
}else{
$response[] = "Document size max 2 MB";
// Error Message for max size

}
}else{
$response[] = "Invalid Document format";
// Error Message for Invalid format size

}
} else{
$response[] = "Please select your Document";
}
if(!empty($response)){
// If response array is not empty means some error occur in
validation than show validation messages
foreach($response as $errorMessage)
{
echo ucwords($errorMessage).'<br/><br/>';
}
exit;
}else{
$uploadedDocumentPath='upload_doc/';
// folder name for document upload

$document=$actual_document_name;
if(move_uploaded_file($tmpDoc,
$uploadedDocumentPath.$actual_document_name)){
// Upload image
$query="insert into contact(name,document,message,inserted_on)
values('$name','$document','$message',now())";
$result=mysql_query($query);
if($result > 0){
echo 'done';
}else{
echo 'Please try after some time<br/>';
}
}else{
echo 'Please Try after some time<br/>';
}
}

dbConnect.inc.php

Contains database connectivity code

$mysql_db_hostname = "Host name";
$mysql_db_user = "UserName";
$mysql_db_password = "Password";
$mysql_db_database = "Database Name";

$con = mysql_connect($mysql_db_hostname, $mysql_db_user,
$mysql_db_password) or die("Could not connect database");
mysql_select_db($mysql_db_database, $con) or die("Could not
select database");
Both comments and pings are currently closed.

49 Responses to “Upload Form using Ajax Jquery”

  1. i really believe you are on the correct track with this one

  2. I really like your writing style, superb information, regards for posting : D.

  3. It’s going to be ending of mine day, but before finish I am reading this great paragraph to improve my knowledge.

  4. You made some decent points there. I looked on the web for more information about the issue and found most individuals will go along with your views on this
    web site.

  5. Way cool! Some very valid points! I appreciate you penning
    this post and the rest of the site is also very good.

  6. This is a great post, I think you should turn it into a 2 or 3 part series.

  7. I love this! So great that I’m definitely coming back again later.

  8. I have read a few good stuff here. Certainly value bookmarking for revisiting. I wonder how a lot effort you place to create this sort of excellent informative website.

  9. Hello, yup this article is actually pleasant and I have learned
    lot of things from it regarding blogging. thanks.

  10. I must thank you for the efforts you’ve put in penning this site. I’m hoping to view the same high-grade blog posts by you in the future as
    well. In fact, your creative writing abilities has motivated me
    to get my own website now ;)

  11. Hey very nice blog!

  12. You’re so awesome! I do not believe I’ve truly read something like this before.
    So great to find somebody with a few unique thoughts on
    this topic. Seriously.. thanks for starting this up. This web site is one thing that’s needed on the internet, someone with a little originality!

  13. It’s actually a nice and useful piece of info. I am glad that you simply shared this helpful information with us. Please keep us up to date like this. Thanks for sharing.

  14. This site was… how do you say it? Relevant!! Finally I have found something which helped me.

    Thanks a lot!

  15. I do not even know how I ended up here, but I thought this post was great.

    I don’t know who you are but definitely you are going to a famous blogger if you aren’t
    already ;) Cheers!

  16. Hurrah! At last I got a webpage from where I know how to genuinely get useful facts concerning my study and knowledge.

  17. Thanks for your marvelous posting! I truly enjoyed reading it,
    you are a great author.I will always bookmark your
    blog and will eventually come back from now on.
    I want to encourage yourself to continue your great writing,
    have a nice day!

  18. Hurrah! After all I got a webpage from where I be
    able to really obtain helpful data regarding my study and knowledge.

  19. Nice replies in return of this difficulty with
    genuine arguments and explaining everything
    concerning that.

  20. This post is really a nice one it assists new web visitors, who are wishing
    in favor of blogging.

  21. Touche. Sound arguments. Keep up the amazing work.

  22. I have read so many articles or reviews about the blogger
    lovers however this post is actually a pleasant post,
    keep it up.

  23. It’s going to be end of mine day, however before finish I am reading this impressive post to increase my know-how.

  24. It’s not my first time to visit this website, i am browsing this web site dailly and obtain nice information from here daily.

  25. There is definately a great deal to find out about this topic.
    I like all the points you have made.

  26. I’m more than happy to discover this page. I want to to thank you for your time for this particularly wonderful read!! I definitely enjoyed every little bit of it and i also have you saved as a favorite to look at new stuff on your site.

  27. Quality posts is the important to attract the users to visit the website, that’s what this web site is providing.

  28. Wonderful рost! We will bе linking to
    this great post on ouг site. Keep up the good wrіting.

  29. Nice post. I learn something totally new and challenging on blogs I stumbleupon every day.
    It’s always helpful to read through articles from other writers and use a little something from their websites.

  30. Lovely just what I was looking for.

  31. Amazing issues here. I am very glad to see your article.
    Thanks a lot and I’m having a look forward to touch you. Will you please drop me a mail?

  32. Usually I don’t write-up on blogs, but I would like to say that this write-up very forced me to accomplish so! Thanks, quite nice article.

  33. Hello. magnificent job. I did not anticipate this. This is
    a excellent story. Thanks!

  34. Thanks in support of sharing such a nice opinion, paragraph is fastidious, thats why i have read it fully

  35. Hello, thе ωhole thing іѕ going nicely hегe and ofcourse еvery one is sharing facts, that’s genuinely excellent, keep up writing.

  36. I do believe all of the ideas you have introduced on your post.
    They’re very convincing and will definitely work. Nonetheless, the posts are very brief for newbies. May just you please extend them a little from subsequent time? Thanks for the post.

  37. Hi there Dear, are уou genuinely visіting thiѕ webѕite гegularly, іf so afteгward
    you wіll ԁefinіtely obtain nice expeгiencе.

  38. We’re a gaggle of volunteers and starting a brand new scheme in our community. Your web site provided us with valuable information to work on. You’ve performed a formidable process and our entire community will likely
    be grateful to you.

  39. I’m now not sure where you are getting your info, but good topic. I needs to spend a while studying much more or understanding more. Thanks for wonderful information I used to be looking for this information for my mission.

  40. I just like the helpful info you provide for your
    articles. I’ll bookmark your blog and check once more here frequently. I’m relatively sure I will learn many new stuff proper right here!

    Good luck for the next!

  41. Hi, this weekend is good for me, since this moment i am reading this great educational article here
    at my residence.

  42. Thanks foг ones marvelous posting! I quite еnjoyed rеading it, you are а greаt author.

    I will makе suгe to bοоkmаrk your blοg and will often сomе back in the future.
    I want to encοurаge you to ultimately cοntinue уοur great job, hаve a nice moгning!

  43. Great write-up, I’m regular visitor of one’s web site, maintain up the excellent operate, and It is going to be a regular visitor for a lengthy time.

  44. I have not checked in here for some time since I thought it was getting boring, but the last few posts are good quality so I guess I will add you back to my everyday bloglist. You deserve it my friend :)

  45. Simply wanna admit that this is very helpful , Thanks for taking your time to write this.

Domains @ Rs.99