I am trying to upload an image using Ajax to a server. I know the code to upload a file using Cakephp, but first I just want to make sure the data / file is uploaded to the server, for example by printing formdata. But it seems that only the data entered in the text box is placed, not the selected file. Any help would be greatly appreciated. Code binding below
HTML
<form id="newcatform" method="post" action="<?php echo($this->Html->url(array('controller'=>'ajaxadmin','action'=>'newcategory'))); ?>" enctype="multipart/form-data">
<div class="row" style="margin-top:20px;">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<h5>Create Category</h5>
</div>
<div class="panel-body">
<div class="form-group" style="padding:15px 0px;">
<label class="col-lg-3 control-label">Category Name</label>
<div class="col-lg-9">
<input type="text" name="newcatname" id="newcatname" class="form-control input-sm valid">
</div>
</div>
<div class="form-group" style="padding:15px 0px;">
<label class="col-lg-3 control-label">Category Image</label>
<div class="col-lg-9">
<input type="file" name="newcatimage" id="newcatimage">
</div>
</div>
<div class="form-group" style="padding:15px 0px;">
<label class="col-lg-3 control-label"> </label>
<div class="col-lg-9">
<button type="submit" class="btn btn-primary btn-sm">Create</button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
Js
$('#newcatform').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData($('#newcatform')[0]);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
In the action controller
if($this->request->is('post')){
$this->Layout=null;
$this->autoRender=false;
$formdata=$this->request->data;
print_r($formdata);
exit;
}
source
share