peter flanagan
peter flanagan

Reputation: 9790

upload image to folder using php and ajax issue with php

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);
      }
    });
  }
});

Upvotes: 2

Views: 349

Answers (1)

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

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:

Upvotes: 2

Related Questions