1

I'm trying to upload an image to a database using AJAX and PHP. When I click on a form's submit button, ajax should send the image's information to a php page where it will be inserted into a database. Here's the form for the image upload:

<form enctype='multipart/form-data' class='img-form'>
<input type='hidden' name='size' value='1000000'>
<input type='file' name='image' id='file-input' class='profile-file'>
<input type='submit' name='upload' value='Upload Image' id='submit-input'>
</form>

Then, when I click on the form's submit button/input type, I send an ajax request by calling a function I put the request in:

$(".img-form-container").on("click", "#submit-input", function(e) {

    e.preventDefault();

    setImage();
}

Here's the setImage() function:

function setImage() {

    var sessid = "<?php echo $_SESSION['id'] ?>";

    $.ajax({
        url: 'includes/profile/set_image.php',
        type: 'POST',
        data: {sessid: sessid},
        success: function(data) {
            console.log("successful image update");
        },
        error: function(requestObject, error, errorThrown) {
            console.log(error);
            console.log(errorThrown);
        }
    });

}

Finally, in a separate file, I have the PHP code that recieves the AJAX request:

    $allowed = ['image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png'];
        if (in_array($_FILES['image']['type'], $allowed)) {

            $sessid= $_REQUEST['sessid'];
            $target = "images/".basename($_FILES['image']['name']);
            $image = $_FILES['image']['name'];

            $q = "INSERT INTO profileimages (image, idUsers) VALUES ('$image', '$sessid')";
            $r = mysqli_query($conn, $q);
        } else {
            echo "<p class='errormsg'>Only JPG and PNG files are permitted.</p>";
    }

The problem is that I need the information needed for the $target and $image variables, but I don't know how to get it from javascript.

I already tried adding some of the PHP code into the JS function setImage() to send over to the PHP file, like so:

function setImage() {

<?php
    if (isset($_POST['upload'])) {

    $target = "images/".basename($_FILES['image']['name']);
    $image = $_FILES['image']['name'];

    }
 ?>

    var target = "<?php echo $target ?>";
    var image = "<?php echo $image?>";
    var sessid = "<?php echo $_SESSION['id'] ?>";

        $.ajax({
            url: 'includes/profile/set_image.php',
            type: 'POST',
            data: {sessid: sessid, image: image, target: target},
            success: function(data) {
                console.log("successful image update");
            },
            error: function(requestObject, error, errorThrown) {
                console.log(error);
                console.log(errorThrown);
            }
        });
});
}

but it gives me this error:

<b>Notice</b>:  Undefined index: image in <b>C:\xampp\htdocs\Real Website\profile.php</b> on line <b>127</b><br />
<br />
<b>Notice</b>:  Undefined index: image in <b>C:\xampp\htdocs\Real Website\profile.php</b> on line <b>128</b><br />

Basically, I need to get the information from the $target and $image variables ($_FILES['image'], etc.) into a javascript variable. Is there a way I can do this?

This system originally worked when I was building my site with plain PHP, but since I've added AJAX, I'm having trouble editing the code to make it work.

Let me know if it would help to add more code or if I made a mistake while posting the code in.

Carson D
  • 81
  • 13
  • first check if you have any data or not. Try echo $_FILES['image']['name']; at the start of your setImage function to see what info you are getting. – Icewine Jul 31 '19 at 00:15
  • 1
    Logic is backwards. Won't see the file in php until after it is uploaded. Need to use FormData API to do upload. See https://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously/8758614#8758614 – charlietfl Jul 31 '19 at 00:49
  • @Icewine I tried this and it gave me this error:
    Notice: Undefined index: image in C:\xampp\htdocs\Real Website\profile.php on line 176
    – Carson D Jul 31 '19 at 00:56
  • @charlietfl I'll look into this – Carson D Jul 31 '19 at 00:57
  • Possible duplicate of [Uploading both data and files in one form using Ajax?](https://stackoverflow.com/questions/10899384/uploading-both-data-and-files-in-one-form-using-ajax) – showdev Jul 31 '19 at 02:35

1 Answers1

0

A good way to send a file to the server in js is to use the formData: follow this https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

when you make

<?php
if (isset($_POST['upload'])) {

$target = "images/".basename($_FILES['image']['name']);
$image = $_FILES['image']['name'];

}

?>

you try to retrieve the absolute name of the file (here a string) then on the server you get this text as an image file that's why PHP cranks a undefined on

$_FILES["image"]

because the value received is a string and not a file.

$_FILES['image']['name'] contains the original name of the uploaded file.

Exple:

var form = $('form.img-form')[0];
var formData = new FormData(form);

or specify exact data for FormData()

var formData = new FormData();
formData.append('size', '1000000');
//Attach file
formData.append('image', $('input[type=file]')[0].files[0]);

now call ajax function

$.ajax({
    url: 'includes/profile/set_image.php',
    type: 'POST',
    data: formData,
    success: function(data) {
        console.log("successful image update");
    },
    error: function(requestObject, error, errorThrown) {
        console.log(error);
        console.log(errorThrown);
    }
});
kevin kemta
  • 90
  • 10
  • This is a much easier way. Thanks. Can you take a look at the code I edited in at the bottom of my question? I'm having trouble sending data to the PHP page. Let me know if there's any confusion with the question. – Carson D Jul 31 '19 at 19:36
  • Never mind, I just figured it out. I have to put that information within the form. – Carson D Jul 31 '19 at 22:04