How to Upload an Image Using AJAX Without Converting It to Base64 in PHP

This article will teach us how to upload an image using AJAX without converting it to base64 in PHP. Uploading an image is a common task in web development, and AJAX is a popular technique used to upload files asynchronously without requiring the user to leave the current page.

We will use a combination of HTML, jQuery, and PHP to upload an image using AJAX without converting it to base64 in PHP. We have created an HTML form that contains an input file element to select the image file to be uploaded and use jQuery to handle the form submission event and send the image file to the server using AJAX. Then use PHP to process the uploaded image file and store it on the server.

If you want to make an Ajax call without waiting for a response please check out the article – jQuery Ajax Call Without Waiting For Response in PHP

Step 1

Let’s get started by creating an HTML form that allows the user to select an image file:

In the HTML code, we create a form with an input file element to select the image file to be uploaded and add a submit button and a div element to display the response message from the server.

Use jQuery to handle the form submission event and create a new FormData object to send the image file to the server using AJAX and then append the selected image file to the FormData object using the append() method.

When we send the AJAX request using the $.ajax() method. We set the URL of the server-side script to handle the file upload to “upload.php”. We also set the type of the request to “post” and the data property to the FormData object we created earlier and set the contentType and processData properties to false to prevent jQuery from automatically processing the data or setting the content type. Finally, we define a successful callback function that displays the response message from the server in the div element.

Step 2

Now that we have created the HTML code, let’s create the PHP code to process the uploaded image file:

In the PHP code, we check if the uploaded image file has any errors. If there are no errors, we generate a unique file name and move the uploaded file to the target directory. We then send a success message back to the client. If there is an error uploading the image, we send an error message back to the client.

Note that you must create a directory named “uploads” in the same directory as the PHP script to store the uploaded images.

In conclusion, we have learned how to upload an image using AJAX without base64 in PHP. By sending the image data as a FormData object, we can avoid encoding the image to base64 and reduce the size of the data being sent to the server. The PHP code that handles the image upload is straightforward and can be modified to meet the needs of your specific application. With this knowledge, you can easily incorporate image-uploading functionality into your web applications.