0

I have a markup like this I am not using form for this now I want to upload an image using ajax

$('#file').on('change', function(e) {
    $.ajax({
        url: "upload.php",
        type: "POST",
        data: ?,
        processData: false,
        contentType: false,
        success: function (response) {
            console.log(response);
        }
    });
})

in data what I have to send? I got this ajax in stack overflow only but I am not able to understand. And one more thing how can I recive the data in PHP file

thank you?

MrCode
  • 63,975
  • 10
  • 90
  • 112
Sujith Wayanad
  • 543
  • 6
  • 20

3 Answers3

1

uploading an image via ajax isn't possible. What you can do is create a hidden iframe and upload the file using that.

DiverseAndRemote.com
  • 19,314
  • 10
  • 61
  • 70
  • 1
    It's definitely possible in modern browsers. – Kevin B Mar 12 '13 at 17:45
  • sorry @KevinB you are correct. If you want to support IE9 and below then its not possible. Maintiaining two solutions for this inorder to support IE9, Firefox 3 and below is quite cumbersome and you probably don't want to go that route. – DiverseAndRemote.com Mar 12 '13 at 18:38
  • Definitely a personal choice at that point. I would use the modern method of doing it, and only degrade functionality for the one browser that doesn't support it. And if you factor this functionality out into a custom method, you only have to do it once. – Kevin B Mar 12 '13 at 18:49
0

do note that generally uploading files via AJAX is a pain. You can view the related question here File Upload via AJAX within JQuery .

Personally, I resorted to generating a hidden iframe on submit, with a clone of the form, which gets submitted. Once done, the content of the iframe is grabbed back to jQuery. I couldn't find another way that workind in old IE versions.

Community
  • 1
  • 1
Nick Andriopoulos
  • 10,313
  • 6
  • 32
  • 56
0

What you are trying to do can be accomplished in browsers that support the FormData function

$('#file').on('change', function(e) {
    var data = new FormData();
    data.append('file',this.files[0]);
    $.ajax({
        url: "upload.php",
        type: "POST",
        data: data,
        processData: false,
        contentType: false,
        success: function (response) {
            console.log(response);
        }
    });
})
Musa
  • 96,336
  • 17
  • 118
  • 137