0

I am trying to save a loaded image on Server Using jQuery,Ajax and PHP.

Here is the code I have for Ajax part:

<script>
        $(function () {
            $("#uploadimage").on('submit', function (e) {
                e.preventDefault();
                var formData = new FormData(this);
                var imgloader = $.ajax({
                    type: "POST",
                    url: "imgLoader.php",
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    beforeSend: function () {
                        console.log(formData);
                    }
                });
                imgloader.fail(function () {
                    console.log('Error');
                });
                imgloader.done(function (data) {
                    $('#res').text(data);
                });

            });

        });

</script>

and I have this PHP on imgLoader.php

<?php

if (isset($_FILES["file"]["type"])) {
    $file = $_FILES['file']['tmp_name'];
    $newloc = "newupload/" . $_FILES['file']['name'];
    move_uploaded_file($file, $newloc);
} else {

    echo 'There is Something Wrong?!';
}
?>

but I am getting the

There is Something Wrong?!

on the page without uploading the image on server. Can you please let me know what I am doing wrong? (I know this is not a secure and safe way to upload image to server, but please be informed that I am trying to lean the whole process of uploading without validation, sanitizing or filtering)

Thanks

mario
  • 144,265
  • 20
  • 237
  • 291
Behseini
  • 6,066
  • 23
  • 78
  • 125

1 Answers1

0

AJAX doesn't do file uploads. It's not designed for that. For uploading files without page refreshing you will have to use any jquery ajax plugin.For e.g.

http://www.malsup.com/jquery/form/

This problem is already discussed in following link:

PHP and Ajax file upload - Can't get the tmp_name with $_FILES

Community
  • 1
  • 1
Gaganpreet Kaur
  • 371
  • 1
  • 3
  • 15