Upload image using AJAX in PHP

PHP and AJAX have been lately great combination. While PHP is a server-side language and AJAX is client-side. AJAX can also be called a medium to communicate with PHP. I guess most of you have done AJAX call to fetch and insert data in the backend. But in this article, you will see how to upload image using AJAX in PHP.

Without any further ado, let’s start.

Upload image using AJAX in PHP
Our directory structure.

I am assuming you have a PHP and MYSQL (XAMPP) installed on your system.

Create a form

Lets create a file named index.html and add the following code in it.

            <p id="msg"></p>
            <input type="text" name="title" />
            <input type="file" id="file" />
            <input type="submit" name="submit" value="submit" />

I havent added any styles , if you like you could do so. We have a now a form with input title and input type file with submit button. Now lets add upload functionality.


To use ajax you gonna need JQuery library.


Now we need to create submit.php file.

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
            $(document).ready(function () {
                    $('form').submit(function (e) {
                        const title = e.target.title.value;
                        let file_data = $('#file').prop('files')[0];
                        var form_data = new FormData();
                        form_data.append('file', file_data);
                        form_data.append('title', title);
                            url: "submit.php",
                            type: "POST",
                            data: form_data,
                            contentType: false,
                            processData: false,
                            success: function (data) {
                                data = JSON.parse(data)
                                var result = '';
                                if (data.success) {
                                    result = data.success;
                                } else {
                                    result = data.failed;

Upload file and save data to database.

Our final step is a little bit code of PHP and MySQL. So I have created a database with a table named data. Now data table consisting of three columns id, title, and imgname. Let’s add these codes in the submit.php file.

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ajaxUpload";//put your db name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

if (isset($_POST['title'])) {
    $title = $_POST['title'];
    $uploads_dir = './images';//create a folder to store images
    $tmp_name = $_FILES["file"]["tmp_name"];
    $filename = basename($_FILES["file"]["name"]);
    move_uploaded_file($tmp_name, "$uploads_dir/$filename");
    $sql = "INSERT INTO data (`title`, `imgname`)
    VALUES ('$title', '$filename')";

    if ($conn->query($sql) === TRUE) {
        echo json_encode(array('success' => "New record created successfully"));
    } else {
        echo json_encode(array('failed' => "Error: " . $sql . "<br>" . $conn->error));

Let’s have some explanation here. So to begin with firstly we have set up a connection with our database. $conn variable is holding the connection instance throughout the code. Next, we have a condition to check whether title is sent through POST request or not if(isset($_POST['title'])).

Next, create folder images in your project directory because we are uploading a file here using the move_uploaded_file() function. This function will move the uploaded file in the images directory. What we are doing further is quite simple. We firing a MySQL query to save title and filename in our database. Then again we are checking if Query is successful what should be returned to our frontend. We are using json_encode() function to return the array into JSON to the frontend.

That was all about how to upload image using AJAX in PHP. You can follow the same ajax in any framework of PHP. This is how you can also POST data along with files in AJAX.

Hope this helped you. In case of any query leave comment in the below comment box.

See also

Leave a Reply

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