2

I have a form, with a file input, that submits just fine when I use the default action to submit the form. But, when I use JQuery and AJAX to make the call to the PHP file, it does not seem to get the file. Is there something that I need to add for sending files through JQUERY/AJAX?

My HTML:

<form id="photo-form" enctype="multipart/form-data" method="post" action="">
    <input type="hidden" name="MAX_FILE_SIZE" value="5000000"/>
    <input type="file" class="upload-input" name="upload-new-input" autocomplete="off"/>
    <input type="submit" name="submit" value="submit/>
</form>

My JQuery:

$(document).ready(function() {
    $("#photo-form").submit(function(e) {

        e.preventDefault();

        var dataString = $(this).serialize();

        $.ajax({  
             type: "POST",  
             url: "uploadcover.php",  
             data: dataString,
             async: false,
             success: function(data) {
                 alert(data);
             }
        }); 

    });
});
user3259283
  • 95
  • 1
  • 9

2 Answers2

4

You can use FormData to upload file with data

Here is sample code

JQuery

$("#photo-form").submit(function(e) {
        e.preventDefault();
        var formData = new FormData($(this)[0]);

        $.ajax({  
             type: "POST",  
             url: "uploadcover.php",  
             data: formData,
             async: false,
             cache: false,
             contentType: false,
             processData: false,
             success: function(data) {
                 alert(data);
             }
        }); 
        return false;
})

You can get it on PHP

PHP CODE

$Img = $_FILES['upload-new-input'];

You can see tutorial Uploading files with jquery ajax

Hope It helps you :)

Krunal Panchal
  • 778
  • 7
  • 14
0

You cannot access file directly.

You can use a plugin, to do this for you, i.e. https://github.com/blueimp/jQuery-File-Upload

Also, in html5 it is possible to access a file from file input as a blob. You can than send it using formData.

More info here: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects

Xardas
  • 142
  • 9