How to upload files in PHP using Ajax simply

This tutorial will give you easiest way to upload files using ajax and PHP. For this you need jquery.form.js and jquery.min.js files.


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script>
jQuery(document).ready(function(){

jQuery('#form').submit(function(e){
alert("test");
e.preventDefault();
jQuery('#form').attr("action","upload.php");
jQuery('#form').ajaxSubmit({
success: function (data) {
alert("Uploaded successfully...");
jQuery("#result").html(data);
}

});
return false;
});

});

</script>
<form id="form" action="" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="text" value="" name="field1">
<input type="submit" value="Submit">
</form>

<div id="result">
</div>

Here is upload.php code for upload the files after submitting.


<?php
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$newFile = substr(time(),0,5)."_test.".$ext;
move_uploaded_file($_FILES['file']['tmp_name'],$filename);
echo "<img src='http://expertwebindia.com/Ajax-File-upload/$filename'>";
?>

Download the the zip for source code here Download Source.

Leave a Reply