-1

I need submit a file for PHP Script using $.ajax({}) JQuery native.

I try to do something like this,

 <input id="my_file" name="my_file" type="file">
//some code
$.ajax({
     type: 'post',
     data: {my_file:$("#my_file").val()}
     url : 'someurl.php'  
});

When I receive the POST variable, it have the filename.

How I can send the file using this way?

user4227199
  • 19
  • 1
  • 3
  • You are missing a comma after the data object – ajmajmajma Nov 11 '14 at 20:41
  • @ajmajmajma you really think that that's the case? Answering the question, you can e.g use HTML5 file uploaders as well, like `Dropzone.js`. Your current behaviour is correct as val() returns filename. – Mike Grabowski Nov 11 '14 at 20:42
  • @MikeGrabowski by the look of his code, he is just puling a value off something, not uploading an actual file, so I was just fixing his syntax :) – ajmajmajma Nov 11 '14 at 20:43
  • Yep, but as long as he receives POST request to the server, it might've been a typo done while writing this question. – Mike Grabowski Nov 11 '14 at 20:44
  • -1 for a poorly worded question and possibly carelessly copying code. – Sparky Nov 11 '14 at 20:58

1 Answers1

0

try this.

// grab your file object from a file input
$('#fileInput').change(function () {
  sendFile(this.files[0]);
});

function sendFile(file) {
  $.ajax({
    type: 'post',
    url: '/targeturl?name=' + file.name,
    data: file,
    success: function () {
      // do something
    },
    xhrFields: {
      // add listener to XMLHTTPRequest object directly for progress (jquery doesn't have this yet)
      onprogress: function (progress) {
        // calculate upload progress
        var percentage = Math.floor((progress.total / progress.totalSize) * 100);
        // log upload progress to console
        console.log('progress', percentage);
        if (percentage === 100) {
          console.log('DONE!');
        }
      }
    },
    processData: false,
    contentType: file.type
  });
}
Prateek
  • 299
  • 3
  • 18
  • Fallow you..., but I try to do something like this in data attribute, {file_user:$("#fileInput").files[o], user:'0'}, and it do not work. I have to send more values from inputs values in this ajax request. Your solution still work then? – user4227199 Nov 11 '14 at 20:56