0

I've been trying to pass an image from ajax to PHP from a file upload in the form.

The following is my ajax call:

var dataString = 'city='+ city_push + '&venue=' + venue_push + '&title=' + title_push + '&subtitle=' + subtitle_push + '&date=' + date_push + '&time=' + time_push + '&price=' + price_push + '&description=' + description_push + '&tag1=' + tag1_push + '&tag2=' + tag2_push + '&email=' + email_push + '&newvenue=' + newvenue + '&password=' + password_push;
    $.ajax({
      type: "POST",
      url: "assets/new.php",
      data: dataString,
      success: function() {
        alert("success");
      }
    });
    return false;

I want to add to my dataString the file so I can process it in the PHP file with $_FILES. Is there a way to do this and maintain the current structure? This ajax code is being called on a successful form submit.

Thanks for your help!

pedrum golriz
  • 518
  • 7
  • 25
  • So from what I gather, there is no way to do this? @sphanley the solution to that one doesn't seem to work (maybe only works in FF) – pedrum golriz May 19 '14 at 17:56
  • Javascript is not allowed to directly access the file system of the machine on which it's running, so no, without using a form to submit it there's no only-Javascript way to do this. – Sam Hanley May 19 '14 at 17:58

1 Answers1

1

Instead of string, you should look into using an object. JavaScript has a FormData object that you can append items to. Append all your data and then you can append your image file like this...

var formData = new FormData();
// add your variable values here using the append method
// Ex: formData.append('key', value);
var imageFile = document.getElementById('yourfileuploadidhere').files[0];
formData.append('image', imageFile);

You'd want to do some type checking on the client end to catch invalid formats and then validate it on the backend as well. Once your formData object is complete, just use data: formData, in your ajax call.

ThomasEllis
  • 358
  • 1
  • 6
  • How would you then get it in the PHP? Would it be $_FILES['image']? Thanks again! I'm a complete noob at ajax, literally started learning last week. – pedrum golriz May 19 '14 at 18:06
  • yes. and the other metadata would exist in the `$_POST` array. `$_POST['city']; $_POST['venue'];` etc where you add each key>value to your `formData`. – ThomasEllis May 19 '14 at 20:35