Search code examples
jqueryajaxformsappendform-data

how to make a file upload NOT required when handling data with jquery Ajax


I have a form like below:

<form name ="order" id="order" action="" method="POST" role="form" enctype="multipart/form-data">
    <input class="checkbox pull-left" type="checkbox" name="check_list[]" value="p1">&nbsp;Product 1
    <input class="checkbox pull-left" type="checkbox" name="check_list[]" value="p2">&nbsp;Product 2
    <input class="form-control name" name="name" type="text" placeholder="name">
    <input class="form-control address" name="address" type="text" placeholder="address">
    <input class="form-control email" name="email" type="email" placeholder="email">
    <input class="form-control phone" name="phone" type="text" placeholder="phone">

    <input type="file" name="image" class="image">
    <button type="submit" id="cf-submit" name="submit" class="btn btn-primary">SUBMIT</button>  
</form>

To send the data to the php file, i use this jquery ajax:

$('#order').on('submit', function(e){
    e.preventDefault();

    var file_name = $('.image').val();              
    var formData = new FormData(this);          
    formData.append('fileupload',$( '.image' )[0].files[0], file_name); // image

    $.ajax({
        url: 'order.php',
        data: formData,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function(data){
            $('.alert-success').show(); 
            $('.alert-success').html(data);

        }
    });

    $('#order')[0].reset();
    return false;
});

All data are processed properly by the php file.

The problem:

I can submit ONLY when a file is chosen to upload. But uploading a file is not required. So people have to choice to send de data from the text fields without uploading a file.

I figured out it has to do something with the formData.append line When i comment out this line, submitting the values of the text fields only is now possible.

So: how can i make the fileupload NOT required, so that it is possible to submit without uploading a file?


Solution

  • if there is now file chosen, there is also nothing to append. So put it in a condition:

    var formData = new FormData(this);
    var file_name = $('.image').val();  
    if(file_name != '') { // if file input is not empty
        formData.append('fileupload',$( '.image' )[0].files[0], file_name); // image
    }