0

I have a really simple HTML page with an image upload form as follows:

<input type='file' id='image_uploaded' accept='image'/>
<input type='submit' id="upload_image"/>

So far for my Javascript, I have:

$(document).ready(function() {
    $("#upload_image").click(function() {
        $.ajax({
            url: "upload.php",
            type: "GET",
            //data: don't know what to put here
            success: function(data) {
                alert(data);
            }
        });
    });
});

upload.php so far is just creating a directory to store images, if the directory does not already exists:

<?php
    define("IMAGE_DIRECTORY", "images");

    //If the directory for images does not exist, create it
    if(!is_dir(IMAGE_DIRECTORY)) {
        mkdir(IMAGE_DIRECTORY, 0777, true);
    }
?>

So I am unsure how to send the image to the PHP script in the Ajax call, and then how do I deal with the image in PHP to save it to the folder?

lillemap
  • 139
  • 2
  • 12
  • So this is two questions... I suggest you research how to deal with images server-side. I'm sure you will find many example online. – NewToJS Apr 05 '17 at 00:27

1 Answers1

0

There are build in variables in PHP to help you with that such as $_FILES so just do this:
First, change your ajax type to "POST" instead of "GET".
Then add these lines of code to store the image:

if(!move_uploaded_file($_FILES["file"]["tmp_name"], "path/to/file/".basename($_FILES["file"]["name"]))){
    die("Sorry, there was an error uploading your file.");
}
Konstantinos
  • 943
  • 1
  • 9
  • 20