Link to home
Start Free TrialLog in
Avatar of Opeyemi AbdulRasheed
Opeyemi AbdulRasheed

asked on

Upload Image and Insert the Directory into MySQL using Ajax

Hello Experts!

I need help on how to effectively upload image to the folder and insert the directory in MySQL Database.

I've tried in many ways. I was able to upload and insert but I don't like the way my code is handling it. I couldn't validate the image properly. I don't know how.

I tried the following but no response:

my html form (modal):
<div class="modal fade" id="modal-media">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Profile Picture</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                    <span class="sr-only">Close</span>
                </button>
            </div>
            <form id="profilePic" action="user_img_controller.php" method="post" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="col-md-12 text-center">
                        <img class="img-circle hs-img-disp profile-image" src="../assets/img/no-photo-3.png" alt="Profile Picture">
                        <div id="updateError"></div>
                        <input type="file" name="fileToUpload" id="fileToUpload" class="profile_img" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
                        <button id="fileSelect" class="btn btn-primary">Select Image</button>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" name="insert_img" id="insert_img" class="btn btn-primary">Insert Selected</button>
                </div>
            </form>
        </div>
    </div>
</div>

Open in new window

php script (user_img_controller.php)
<?php
include('connection.php');

if ( ! empty($_POST) ){

    $response = (object)['message' => '', 'status' => false];

    $target_dir = "staff_img/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
    
    if ( ! isset($_FILES['fileToUpload']) || empty($_FILES['fileToUpload']['name']) ) {
        $update_err = "<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>
            Please select image to upload</div>";
        $response = array( 'success' => false, 'message' => $update_err );
        die( json_encode($response) );
    }

    if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
        && $imageFileType != "gif" ) {
        $update_err = "<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>
            Sorry, only JPG, JPEG, PNG & GIF files are allowed.</div>";
        $response = array( 'success' => false, 'message' => $update_err );
        die( json_encode($response) );
    } 

    if ($_FILES["fileToUpload"]["size"] > 100000) {
        $update_err = "<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>
            Sorry, your file is too large. Maximum of 100KB is allowed!</div>";
        $response = array( 'success' => false, 'message' => $update_err );
        die( json_encode($response) );

    } else {

        move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
        $query = "UPDATE users SET Image_Dir = '".$target_file."' WHERE UserId = '".$_GET['id']."' ";
        $result = mysqli_query($conn, $query);
                
    if (! empty($result)) {
        $response->message = "Profile picture successfully updated";
        $response->status = true;
    } else {
        $response->message = $conn->error;
    }
    die( json_encode($response) );
    }      
}

?>

Open in new window

And Ajax:
$('#insert_img').click(function() {

            $.ajax({
                url      : 'user_img_controller.php',
                method   : 'post',
                data     : $('#profilePic').serialize(),
                dataType : 'json',
            }).done(function(response) {
                var type = response.status ? 'success' : 'danger';
                if (type == 'success') {
                    $('#modal-media').modal('hide');
                    toastr.success(response.message);
                } else{
                    // we have failure
                    $('#updateError').html(response.message);
                    $("#updateError").fadeTo(5000, 500).slideUp(500, function(){
                        $("#updateError").slideUp(500);
                    });
                }

            });
            
        });

Open in new window

Avatar of Zakaria Acharki
Zakaria Acharki
Flag of Morocco image

You were so close, you need to use FormData Object when you want to send files using ajax request so to send the picture you must create a FormData object then append the fileToUpload to it and attach it to the data like :

$('#insert_img').click(function(e) {
	e.preventDefault();

	var formData = new FormData();
	formData.append('file', $('#fileToUpload')[0].files[0]);

    $.ajax({
        url         : 'user_img_controller.php',
        method      : 'post',
        data        : formData,
        mimeTypes   : "multipart/form-data",
        contentType : false,
        cache       : false,
        processData : false,
    }).done(function(response) {
        var type = response.status ? 'success' : 'danger';
        if (type == 'success') {
            $('#modal-media').modal('hide');
            toastr.success(response.message);
        } else{
            // we have failure
            $('#updateError').html(response.message);
            $("#updateError").fadeTo(5000, 500).slideUp(500, function(){
                $("#updateError").slideUp(500);
            });
        }
    });
});

Open in new window

Avatar of Opeyemi AbdulRasheed
Opeyemi AbdulRasheed

ASKER

Hello Zakaria, thanks for your help.

I tried it. When I click without selecting any image, I got:
Notice: Undefined index: fileToUpload in C:\...\user_img_controller.php on line 9

When I select image, no response.

What am I doing wrong, please?
Hi @AbdulRasheed,

I'm not sure why you're using  :

onchange="handleFiles(this.files)"

Open in new window


And how you connect the "fileSelect" button with the file input field, I need to see the "handleFiles" and we need to make sure that the $('#fileToUpload')[0].files[0] will return something or not.

Let us start with simple check like :

$('#insert_img').click(function(e) {
	e.preventDefault();

	console.log( $('#fileToUpload').val() );
}

Open in new window


Share the console output with us.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.