0

I understand this question gets asked a lot, but none of the solutions I have tried have worked out for me and I would really appreciate some help.

I want to upload an image to store it in a database, and using Ajax to do so is the neatest way to do so without reloading my page.

HTML

<div class="card">
   <form method="POST" id="imgupload" action="" name="imgupload" enctype="multipart/form-data">         
      <input type="file" name="myimage" id="myimage">
      <input type="button" id="doUpload" value="Upload" onclick="uploadImage()">
   </form>
</div>

JS/JQuery

function uploadImage()
{
    let = myData = new FormData();
    let files = $('#myimage')[0].files;
    console.log("here >> ");
    console.log(files);

    if(files.length > 0 )
    {
        myData.append('file',files[0]);

        $.ajax
        ({
            url: 'config.php',
            type: 'post',
            data: {uploadImage: myData},
            contentType: false,
            cache: false,
            processData: false,
            success: function(output)
            {
                console.log(output);
                console.log("----");
            }
        });
    }else
    {
        alert("Sorry, please choose a picture first!");
    }
};

config.php

//function to upload an image
if(isset($_POST['uploadImage']) && !empty($_POST['uploadImage']))
{
    $configMyDB->select_db($configDBName);

    $myImage = $_POST['uploadImage'];
    echo("<<");
    echo($myImage);
    echo(">>");
}

I have a lot of other functions in my PHP so I know that there are no issues connecting to the database.

My problem is that the Ajax call is not successful and I have no idea why. Here is my output in console log:

line:141 here >> 
line:142 FileList {0: File, length: 1}
line:158 
line:159 ----

I have been scratching my head for the past couple of hours to no avail. Sending in a string returns the proper result. I assume it has something to do with FormData, as $('#myimage')[0].files shows the correct info in the console log. Furthermore, doing a console log of FormData gives me a really long and ugly array, in which I cannot find my image information.

Any help would be greatly appreciated as my deadline for this is looming. I am not allowed to use any libraries, or any other technology apart from what I am currently using.

  • Have you checked the network tab in your browser's dev tools? It seems like you're sending the string `[object Object]`. Does this solve your problem [How to send FormData objects with Ajax-requests in jQuery?](https://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery?) You have to set `data: myData,` – jabaa Nov 13 '21 at 23:49

0 Answers0