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

3
  • your form must contain enctype="multipart/form-data", is it ? Commented Mar 26, 2015 at 4:07
  • Hi yiiframe, yes it has <form id="uploadimage" action="" method="post" enctype="multipart/form-data"></form> Commented Mar 26, 2015 at 4:11
  • What does your console log says and open chrome in developer mode and tell what is the response from network tab Commented Mar 26, 2015 at 5:44

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.