Upload image using AJAX and PHP

Uploading image on server using Ajax and PHP inside a form can be done using many jQuery plugins available on the Internet. Some programmers do not use them. As they become heavy due to server to browser load time and sometimes configuration problems. Most of them are not configured to upload image with text. They upload only images and you have to send text separately to save image with text in the database.

Here you will learn how to upload image as well as input text or textarea content to save in the database, is not easy for some of newbie programmers. Though it is very simple and can be done using simple AJAX and PHP. Let’s look inside the coding…

First look at the form


This form is simple form with name and image fields. Name is any name of the user and file is to browse from the device and submit the form. Now we will upload this image with full name data using AJAX. You will have to add the jQuery library link in the HTML page. Look at the form below.

The above Ajax script is simply creates an object of the form and then sends it to URL file for processing. The FormData interface provides a way to construct the key value pair and send them using the Ajax method. Setting processData to false means you are sending DOMDocument or some non-processed data. While sending data to the server the contentType is always set to “application/x-www-form-urlencoded; charset=UTF-8″. So for uploading thing, it should be set to false to tell jQuery to not set any content type header.

Now the file is sent to server and you have to parse it and save it to your local folder. At the same time you can save the text sent along with the image. You can get the tmp image $_FILES[‘filename’][‘tmp_name’] and real name of the image by accessing $_FILES[‘filename’][‘name’]. You just need to rename the file if it is required or can save the same name as it is sent to the server. And the text as $_GET[‘full_name’] that can be assigned to some variable and then can be saved to table.

PHP save.php


One more thing that every novice programmer does that they forget to add enctype in the form. And now as the file name is known and the full name of the user is also known they can be saved into the table.

Now you see how simple is to upload image with text on server. No heavy jQuery plugins and css files to upload, just the use of jQuery library settings and all are done.

June 11, 2017 by suman singh

Add a Comment

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