Insert Image into Database without Form Submit AJAX PHP


#1

I’m trying to insert an image from an type=‘file’ HTML tag into an MySQL database using AJAX.

I’m new to using AJAX for image uploads and i think im getting the syntax wrong somewhere.

I’ve done some research on this and i think I’m close.

HTML:

 <input type="file" id="HTMLmyimage"> 

AJAX:

 var $file_data = $('#HTMLmyimage').prop('files')[0];   
    var $form_data = new FormData();                  
    $form_data.append('file', $file_data);



$.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        processData: false, // important
        contentType: false, // important
        url: "PHPURL",
        data: { 
            'BEimage': $form_data,
        },
        success: function(result) {
            alert('User Added')
        },
        error: function(result) {
            alert('error');
        }
    });

PHP:

$image = $request->getParam('BEimage');

$imageData = (file_get_contents($_FILES[$image]['tmp_name']));

$sql4 = "INSERT INTO customerlocation (CustomerID, Username, img) VALUES ('$CustomerID', '$Username', :img)";
     $stmt4 = $db->prepare($sql4);  
     $stmt4->bindParam(':img', $imageData);
     $stmt4->execute();

My current error is saying that $image is not defined but im not sure if im even doing anything before that correct.

Any help on this would be brilliant :slight_smile:

Thank you