Updated on Kisan Patel
This tutorial will explain you how to upload file with ajax using jQuery and PHP?
In jQuery there is no ajax method that can upload file. so we need to use iframe to load the ajax functionality.
In this demo, we have create file.php file and add the below line of html code:
<form action="uploadFile.php" target="uploadIframe" method="post" enctype="multipart/form-data"> <div class="fieldRow"> <label>Select the file: </label> <input type="file" name="file" id="file" onChange="submitForm(this)" /> </div> </form> <iframe style="border:0;" id="uploadIframe" name="uploadIframe"></iframe> <div id="successMessage"></div>
In above code, we have called submitForm()
function on file input onChange
event:
<script> function submitForm(upload_input_field){ upload_input_field.form.submit(); upload_input_field.disabled = true; return true; } <script>
The complete code in the file.php file:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery Navigation</title> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script> function submitForm(upload_input_field){ upload_input_field.form.submit(); upload_input_field.disabled = true; return true; } </script> </head> <body> <form action="uploadFile.php" target="uploadIframe" method="post" enctype="multipart/form-data"> <div class="fieldRow"> <label>Select the file: </label> <input type="file" name="file" id="file" onChange="submitForm(this)" /> </div> </form> <iframe style="border:0;" id="uploadIframe" name="uploadIframe"></iframe> <div id="successMessage"></div> </body> </html>
In above script, we have submit the form. Now, create new php file uploadFile.php
for uploading file and add the below line of code:
<!doctype html> <html lang="en"> <head> <script src="//code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <?php $upload_dir = "uploads"; $result["status"] = "200"; $result["message"]= "Error!"; if(isset($_FILES['file'])){ echo "Uploading file... <br />"; if ($_FILES['file']['error'] == UPLOAD_ERR_OK) { $filename = $_FILES['file']['name']; move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir.'/'.$filename); $result["status"] = "100"; $result["message"]="File was uploaded successfully!"; } elseif ($_FILES['file']['error'] == UPLOAD_ERR_INI_SIZE) { $result["status"] = "200"; $result["message"]= "The file is too big!"; } else { $result["status"] = "500"; $result["message"]= "Unknown error!"; } } ?> <script> $(function () { $('#successMessage', window.parent.document).html('<?php echo htmlspecialchars($result["message"]); ?>'); }); </script> </body> </html>
In above code, you can see we have used iframe, to which we are submitting the form.
When upload is successful, we will display the success message using below script:
<script> $(function () { $('#successMessage', window.parent.document).html('<?php echo htmlspecialchars($result["message"]); ?>'); }); </script>
The output will look like this: