Reputation: 52
I'm unable to upload the image by ajax,it always redirect to the page whenever I click submit button and the data is not added to the database as well.
form
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>" id="ImageUploadForm" enctype="multipart/form-data">
<input type="text" name="caption" id="caption">
<input type="file" name="image" id="ImageBrowse"/>
<input type="submit" class="btn btn-success" value="Save" />
</form>
ajax
$(document).ready(function (e) {
$("#imageUploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "<?php echo base_url();?>adminpromisess/addgal",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data) {
alert(data);
//$("#gallery-form").load(".gallery-form");
},
error: function() {
}
});
}));
});
add data to database function (controller)
public function addgal(){
$caption = $this->input->post('caption');
$promises = 00;
$description = $this->input->post('description');
$image = $_FILES['image']['name'];
if(move_uploaded_file($_FILES['image']['tmp_name'], 'assets/img/upload/promises_image/'.$image)){
$data = array(
'caption' => $caption,
'promises' => $promises,
'gal_desc' => $description,
'image' => $image
);
$result = $this->adminpromisesmodel->addGallery($data);
}else{
echo "Fail to upload file";
die();
}
}
note:model (query) to save the database is correct so i didn't post it
Upvotes: 0
Views: 239
Reputation: 377
Try this
$('#imageUploadForm').on('submit', function(ev){
ev.preventDefault();
var forms = document.querySelector('form#imageUploadForm');
var request = new XMLHttpRequest();
var formDatas = new FormData(forms);
request.open('post','yourControllerFunction');
request.send(formDatas);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
//Request was OK show success message
} else {
// Request not OK, show error message
}
}
});
In your controller's action (its a cakephp code)
if($this->request->is('post')){
$data = $this->request->data;
echo "<pre>",print_r($data),"</pre>";
//You should be able to see file data in this array
}
You can handle it just like a direct form submission on your controller
Upvotes: 1
Reputation: 2735
ImageUploadForm
!= imageUploadForm
Fix that typo causing the dead code (the form tag) to run and things should work as you expect. Your browser, development tools, network tab should have shown a POST instead of a XHR because of that issue.
Upvotes: 0