0

I'm trying to upload a file and variable value with ajax but it doesn't send. Currently, I'm using form and submit is, but I need to pass this variable body - to get body's width. How to do that using Ajax?

My code is:

$(document).ready(function (e) {
    $("#form").on('submit',(function(e) {
      var file = new FormData($('form')[0]);
      var body = $('body').width();

        e.preventDefault();
        $.ajax({
            url: "image/upload",
            type: "POST",
            data:  {body:body, file:file},
            contentType: false,
            cache: false,
            processData:false,
            success: function(data){

            }           
       });
    }));
});
<form id="form">
    <label>Upload Image File:</label><br/>
    <input name="image" type="file" />
    <input type="submit" value="Submit" />
</form>

My controller is:

     public function action_create()
     {
          $error = 'false';
          $bg_path = '';
          if(!empty($_FILES["file"]))
          {
 if ((($_FILES["file"]["type"] == "image/jpeg")
                    || ($_FILES["file"]["type"] == "image/jpg")
                    || ($_FILES["file"]["type"] == "image/pjpeg")
                    || ($_FILES["file"]["type"] == "image/x-png")
                    || ($_FILES["file"]["type"] == "image/png"))
                && in_array($extension, $allowedExts)) {
               if ($_FILES["file"]["error"] > 0) 
               {
                    $error =  "Error: " . $_FILES["file"]["error"] . "<br>";
               } 
               else 
               {
                    $date = date('YMd');
                    $path = DOCROOT.'assets/uploads/'.$date.'/';
                    if (!file_exists($path)) {
                         mkdir($path, 0775);
                    }
                    //other code
               }
}
      }
ivva
  • 2,819
  • 9
  • 31
  • 64
  • See [jQuery Ajax File Upload](http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload) and other posts linked from its comment section. – showdev Dec 09 '15 at 21:53

1 Answers1

1

You should append the body variable to the FormData you're sending, not as part of an object. Try this:

$("#form").on('submit', function(e) {
    e.preventDefault();
    var formdata = new FormData($('form')[0]);
    formdata.append('body', $('body').width());

    $.ajax({
        url: "image/upload",
        type: "POST",
        data: formdata
        contentType: false,
        cache: false,
        processData: false,
        success: function(data) {
            console.log('request successful!'); 
        }           
    });
});

Also note that you need to set the enctype attribute of the form as you're including a file in the data:

<form id="form" enctype="multipart/form-data">
    <label>Upload Image File:</label><br/>
    <input name="image" type="file" />
    <input type="submit" value="Submit" />
</form>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339