0

I newbie in this webpage area and I was try to upload image to my file by using ajax and send it to php. But I have done some coding here. Can some one correct me where I'am wrong ? here is my form with file upload and a button

<form method="post" enctype="multipart/form-data"  action="">
    <input type="file" name="images" id="images" multiple="" />

    <input type="submit" value="submit" id="harlo">
</form>

Once I click on button the file will send it here and receive the src and ajax to php file but I guess is about getting source problem. Need some one correct it for me.

(function upload() {

    var input2 = document.getElementById("harlo"), 

    formdata = false;



    if (window.FormData) {
        formdata = new FormData();

    }

    input2.addEventListener("click", function () {

        var i = 0, len = $('input[type="file"]')[0].files;

        for ( ; i < len.length; i++ ) {
            file = len.files[i];

            if (formdata) {
                formdata.append("images", file);
            }

        }

        if (formdata) {
            $.ajax({
                url: "upload.php",
                type: "POST",
                data: formdata,
                processData: false,
                contentType: false,
                success: function (res) {
                    document.getElementById("response").innerHTML =  res; 
                }
            });
        }
    }, false);
}());

<?php

    foreach ($_FILES["images"]["error"] as $key => $error) {
        if ($error == UPLOAD_ERR_OK) {
            $name = $_FILES["images"]["name"][$key];
            move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
        }
    }

    echo "<h2>Successfully Uploaded Images</h2>";
?>
showdev
  • 28,454
  • 37
  • 55
  • 73
user3149572
  • 9
  • 1
  • 5

1 Answers1

0

Use something like:

$("form").on("submit", function(
    // Your ajax request goes here
    $.ajax({
        url: "upload.php",
       type: "POST",
       data: $("form").serialize(),
       processData: false,
       contentType: false,
       success: function (res) {
          $("#response").innerHTML = res;
       }
    });

    return false;
));

But there seems to be a problem with sending files trough ajax anyway. Cause they're missed by the serialize() method because JS has no access to files content on users computer. So the form must be sent to the server to get the file data.

See here: https://stackoverflow.com/a/4545089/1652031

Community
  • 1
  • 1
TiMESPLiNTER
  • 5,741
  • 2
  • 28
  • 64