How to transfer a file from input type = file using ajax or post using the POST file to a php file I can’t find and do anything sensible.

I'm trying this way, but something comes out of nothing good.

$.ajax({ url: "ajax.php", type: "post", data: "upload_file="+$('#file')[0].files[0], success: function(){ }, error: function (jqXHR, exception) { } dataType: "json" }); 

I try to catch php like that

 $_FILES['upload_file']['tmp_name'] 

    1 answer 1

    This allows FormData to do

     $.ajax({ url: "ajax.php", type: "post", data: new FormData($('#file').parents('form:first')[0]), /*при использовании FormData флаги processData и contentType надо ставить в false*/ processData: false, contentType: false, success: function(){ }, error: function (jqXHR, exception) { } dataType: "json" }); 

    I only advise you to research for compatibility first http://caniuse.com/#feat=xhr2

    UPD:
    Corrected the code. With such a request in PHP, then you have to work with $_FILES['file'] - as usual.

    • And how to catch it in php in this way? - Vladimir Alexandrov
    • @ Vladimir Aleksandrov Catch also. Through $ _FILES. - Arnial
    • @Arnial, this is understandable by what name? Specified in the input? - Vladimir Alexandrov
    • @ Vladimir Alexandrov name of the input, do not forget to specify, of course. Under that name in $ _FILES it will be - Goncharov Alexander