2

I'm very new to Ajax and PHP. I'm using below code to submit my HTML form via Ajax but image files aren't passed through. I tried adding contentType in the code still no luck. Please help can I use the same code (with tweaks) to submit the image files along with text inputs?

Here is the code:

$(document).ready(function() {
    $("#submit_form").submit(function() {       
        $.ajax({
            type: "POST",
            url: 'inc/submit_form.php',
            data:$("#submit_form").serialize(),
            success: function (data) {  
                // Inserting html into the result div on success
                $('#form-result').html(data);
            },
            error: function(jqXHR, text, error){
            // Displaying if there are any errors
                $('#form-result').html(error);           
        }
    });
        return false;
    });
});
halfer
  • 18,701
  • 13
  • 79
  • 158
Rehmat
  • 3,732
  • 1
  • 16
  • 32

1 Answers1

2

This is only the AJAX section of the script, but this is what I have used in the past. I've commented each line for an explanation:

<script type="text/javascript">

var files = $('#TARGET_TO_FILES_INPUT').prop('files');

var data = new FormData();

$.each(files, function(key,val){
    data.append(key,val);
});


$.ajax({
    type:"POST",// post method
    url:UPLOAD_FILE,// path to file upload
    data:data,// image and any other form data
    cache:false,// stop any caching of browser
    dataType:'json',// return json when complete
    processData:false,// stop preprocessing of data by jquery (ie querystring)
    contentType:false,// must be set to false; turns off default "application/x-www-form-urlencoded; charset=UTF-8"
    success:function(o){
        // successful upload stuff goes here
    },
    xhr:function(){
        var xhr = $.ajaxSettings.xhr() ;

        xhr.upload.onprogress = function(evt){ 
            //progress bar stuff goes here
        }
        xhr.upload.onload = function(){
            //just before upload stuff goes here
        }

        return xhr ;
    }
});

</script>
Samuel Cook
  • 15,511
  • 6
  • 43
  • 58