2

I am trying to upload a photo using ajax and php. Following other answers here it should be fairly straight forward but I cannot get it to work. Can anyone see anything wrong with my code.

The ajax request is successful so I believe it must be an issue with my php.

My html code looks like this

<form>
  <input id="upload-input" type="file" multiple="multiple"></br>
  <input class="auction-description" type="text">
  <input class="btn btn-lg submit-images-btn" type="submit">
</form>

My php code looks like this:

php

<?php
$dir = "/images";
echo $dir;
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"], $dir)
?>

and my js looks like this.

js

$('#upload-input').on('change', function() {

  var files = $(this).get(0).files;

  if (files.length > 0) {
    // create a FormData object which will be sent as the data payload in the
    // AJAX request
    var formData = new FormData();

    // loop through all the selected files and add them to the formData object
    for (var i = 0; i < files.length; i++) {
      var file = files[i];
      fileNames.push(file.name);

      // add the files to formData object for the data payload
      formData.append("image", file);
    }

    $.ajax({
      url: '/uploadphoto.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(data) {
        console.log('upload successful!\n' + data);
      }
    });
  }
});
10
  • For starters, try a system path instead of a url Commented May 18, 2017 at 17:52
  • May you need to pass. => enctype: 'multipart/form-data' in your ajax request. Commented May 18, 2017 at 17:54
  • see if php's error reporting reveals anything and look at your developer console Commented May 18, 2017 at 17:58
  • @Fred-ii- network shows a 200 success for the ajax post. And if I echo something in the php file it shows up as the response Commented May 18, 2017 at 18:00
  • "And if I echo something in the php file it shows up as the response" - Are you running this as http://localhost or as file:///? what does the HTML source reveal? @peterflanagan Commented May 18, 2017 at 18:01

1 Answer 1

2

As per our conversation in chat, the issue turned out that your file's input was not named and a valid enctype.

It should read as <input type="file" name="uploaded_file">

and in the form, to include enctype="multipart/form-data" and a POST method.

<form> without a "POST" method defaults to a GET method.

These are essential/required when dealing with files.

Reference:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.