Ajax file upload form.

We once wrote on How to upload files on your website using a form. Using that method, we noticed that the whole webpage will have to refresh before the form is submitted which might not be a good experience in modern web applications.

Here, we’re going to submit a form containing a file input to ur server using the JavaScript click event. This is possible through the use of Ajax, jQuery and php programming language which we’ll use to submit the files to the server.

Ajax file uploads.

The advantages of his method is that the page won’t have to refresh itself all the time and it is more user-friendly than the other.

Let’s start with creating our database using the phpmyadmin tool in XAMPP.

Creating your MySQL database.

You can easily create your database using the phpmyadmin tool. this is usually found in your cpanel of your website. If you’re using localhost, you can start your Apache servers and type “http://localhost/phpmyadmin“.

The “http://” isn’t necessary, you can skip it if you need to.

We have decided to name our database charmingdesk. Now we’ll create a table in our database, this table will be named “filepaths” which will have 3 columns, “id”, “name” and “paths”.

Now that we’ve created our table, it’s time to move over to our index.php page which well create our HTML form.

Creating our file upload form.

<form method="post" action="submit.php" enctype="multipart/form-data"
id="myform">


<label for="fpath"> file path:</label>

<input type="file" id="fpath" name="fpath"><br><br>


<input type="button" name="Submit"
onclick="submitform()">

</form>

Note: type of the submit button should be set to button.

Now we’ll begin with our submit form function in JavaScript. Make sure jQuery has already been imported to your script for this to work.

<script>

function submitform(){

//Select the element with id (myform).

var myform=$('#myform');

//Compile all form inputs into a variable.

var fd=new formData(myform);

//Now let's send the inputs to our php script named processform.php to handle the php processing.

$.ajax({

type:'post',
url:'processform.php',
data:fd,
processData: false,
contentType: false,
success: function(data){

$('#myform').html(data);


}


});
}



</script>

Let me explain the above block of code here.

  1. Type– used to set the forms submit method, we used “post” because a file upload is involved. If it was just text then “Get” method is preferable.
  2. url: the file path of the script where we want to submit the form values to. This is similar to the action attribute in the form tag.
  3. data: the items you want to submit in the form, we’ve already compiled our form inputs into one variable which we submitted previously.
  4. Process type and content type: they are compulsory when file inputs are involved and they should always be set to false.
  5. Success: This is used to display the results from the processing page if the sending was successful.

Now let’s process our form in the “processform.php” script which handles the uploads and storage.

First we create a file named “processform.php” and connect it to our database.

<?php
$conn=mysqli_query ("hostname", "username", "password", "database name");

?>
The host name is usually localhost, then the rest is given to you by your web hosting company.
If you're using a localhost server, then the following applies for you

username = "root"

password = "" //empty

Database name="your database name".

Here we decided to use charming desk as our database name.

Now that we’ve connected the script to our database, let’s continue with the processing.

$iname=
$_FILES['fpath']['name'];

//Stores the actual file name

$path=
$_FILES['fpath'][' tmp_name'];
//Stores the initial file path

$destination="uploads/";

$newpath=$destination+basename($iname);

If(
move_uploaded_file ($path, $newpath)
){

echo "file uploaded successfully";

//Insert to database.

mysqli_query($conn,"INSERT INTO filepaths (name,path)VALUES ('$iname','$newpath')");

echo "file upload successful.";
}

else{

echo "an error occurred";

}

There you have it. We’ve simply used Ajax with JavaScript to perform a file upload without having to refresh the page. Ajax can also be used for more processes in which minimum amount of data has to be sent without reloading the page like a search bar, online voting website, social media like button etc.

We’ve come to the end of this article, feel free to follow us on Facebook and Instagram to stay updated with our latest posts.

You can also mail us at our official email address hello@charmingdesk.com.ng for a private reply.

Your favorite web developers.


vic okeke

I'm just a web developer hoping to help out junior developers in algorithms for their projects.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *