0

This is my code

                        $.ajax({
                            type: 'post',
                            url: '../lib/upload.php',
                            data: new FormData( $("#niceidentifier") ),
                            processData: false,
                            contentType: false,
                            success: function (response) {
                                if(response == 'success') {
                                    return true;
                                }
                                else {
                                    alert(response);
                                    console.log(response);
                                }
                            }
                        });

The HTML form is just basic HTML (enctype included and method post) but unfortunately NO data is passed. How can I upload a file AND pass the input data once?

user3613095
  • 99
  • 1
  • 12

4 Answers4

0

It's not as simple to pass files and other data, such as text, together in the same POST request. The only way to achieve that is making multipart/form-data request.

http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

nunob
  • 592
  • 7
  • 24
0

You can use FormData to pass the File. and processData,contentType set to false compulsory. because you are not going to process file in client side.

// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
        data.append('myFile', value);   //No I18N
});


$.ajax({
    url: '/your-url', 
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',   //No I18N
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
    {
    // do something
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
            // Handle errors here
    }
});

OR you can send file with data as following:

$( '#formId' )
  .submit( function( e ) {
 e.preventDefault();
 $.ajax({
    url: '/your-url', 
    type: 'POST',
    data: new FormData( this ),
    cache: false,
    dataType: 'json',   //No I18N
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
    {
    // do something
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
            // Handle errors here
    }
});
});
kriyeta
  • 695
  • 4
  • 12
0

I use ajaxForm to upload files asynchronously via ajax, it is much easier than trying to implement your own.

http://malsup.com/jquery/form/

QBM5
  • 2,778
  • 2
  • 17
  • 24
0

For a cross browser solution I think it is better to use

$("#form_id").ajaxSubmit();
Sebri Zouhaier
  • 745
  • 7
  • 18