Cakephp FormData Ajax file upload - ajax

I'm stuck in uploading from data and file using FormData + Ajax + CakePHP
Here is my form:
<form name="multiform" class="frmaddproduct" action="addproduct" method="POST" enctype="multipart/form-data">
<div class="formrow">
<div class="createproductlabel leftfloat">Name</div>
<div class="formcontrol leftfloat"><input type="text" name="name"/><br/><span>Name?</span></div>
<div class="clear"></div>
</div>
<div class="formrow">
<div class="createproductlabel leftfloat">Cost</div>
<div class="formcontrol leftfloat"><input type="text" name="cost"/></div>
<div class="clear"></div>
</div>
<div class="formrow">
<div class="createproductlabel leftfloat">Discount</div>
<div class="formcontrol leftfloat"><input type="text" name="discount" class="discount" maxlength="5"/> %</div>
<div class="clear"></div>
</div>
<div class="formrow">
<div class="createproductlabel leftfloat">Description</div>
<div class="formcontrol leftfloat"><textarea name="description" rows="5"></textarea></div>
<div class="clear"></div>
</div>
<div class='formrow'>
<div class='createproductlabel leftfloat'>Choose file</div>
<div class='formcontrol leftfloat'><input type='file' name=''productpicture'/></div>
<div class='closephotos leftfloat'><img src='../img/close.png' class='closeproductpicture'/></div>
<div class='clear'></div>
</div>
<div class="formrow">
<div class="createproductlabel leftfloat"> </div>
<div class="formcontrol leftfloat"><input type="button" name="btncreateproduct" value=" Create Product "/></div>
<div class="clear"></div>
</div>
</form>
Here is my code for submitting this form:
$(".frmaddproduct").submit(function(e)
{
var formObj = $(this);
var formURL = formObj.attr("action");
if(window.FormData !== undefined) // for HTML5 browsers
{
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
$("#multi-msg").html('<pre><code>'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#multi-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault();
e.unbind();
}
else // for older browsers
{
// generate a random id
var iframeId = 'unique' + (new Date().getTime());
// create an empty iframe
var iframe = $('<iframe src="javascript:false;" name="'+iframeId+'" />');
// hide it
iframe.hide();
// set form target to iframe
formObj.attr('target',iframeId);
// Add iframe to body
iframe.appendTo('body');
iframe.load(function(e)
{
var doc = getDoc(iframe[0]);
var docRoot = doc.body ? doc.body : doc.documentElement;
var data = docRoot.innerHTML;
$("#multi-msg").html('<pre><code>'+data+'</code></pre>');
});
}
});
In firebug, I can see data being sent:
-----------------------------2463414040929 Content-Disposition: form-data; name="categoryproduct" 1 -----------------------------2463414040929 Content-Disposition: form-data;
name="companyproduct" 1 -----------------------------2463414040929 Content-Disposition: form-data;
name="name" AAA -----------------------------2463414040929 Content-Disposition: form-data; name="cost" 34
But when I try to read or dump request data in Controller, I get: Array()
i.e. No data being sent
debug($this->request->data);
also, $this->log($this->request->data["discount"]) gives me blank value
Please help me out on this.
I'm confused where I'm getting it wrong
I didn't used cakephp form helpers to create form

USE the regular $_FILES PHP Server variable

Related

Ajax request for delete image doesnt work in laravel

I want to delete the image in the preview box, as well as delete it in the database using ajax. Deleting the image in the preview box was successful, but deleting it from the database didn't work.
here my ajax:
$(document).ready(function() {
document.getElementById('pro-image').addEventListener('change', readImage, false);
$(".preview-images-zone").sortable();
$(document).on('click', '.image-cancel', function() {
let no = $(this).data('no');
let idData = $(this).data('id');
$(".preview-image.preview-show-" + no).remove();
$.ajax({
type: 'POST',
url: '{{url("unit/API/simpan")}}',
data: {
'id': idData
},
success: function(data) {
alert('success');
}
});
});
});
My Html:
<!-- Percobaan Preview -->
<fieldset class="form-group">
<div class="offset-md-2 col-md-6">
Upload Gambar
<input type="file" id="pro-image" name="gambarku[]" style="display: none;" class="form-control" multiple>
</div>
</fieldset>
<div class="preview-images-zone offset-md-2 col-md-8">
<!-- Gambar Utama -->
<div class="preview-image preview-show-1">
<div class="image-cancel" data-no="1">x</div>
<div class="image-zone"><img id="pro-img-1" src="{{asset('storage/rumah/'.$rumahku->gambar_rumah)}}"></div>
</div>
<!-- Gambar Tambahan -->
<?php $counter = 2 ?>
#foreach($rumahku->gambar as $rows)
<div class="preview-image preview-show-{{$counter}}">
<div class="image-cancel" data-no="{{$counter}}" data-id="{{$rows->id_gambar}}">x</div>
<div class="image-zone"><img id="pro-img-{{$counter}}" src="{{asset('storage/rumah/'.$rows->gambar_unit)}}"></div>
</div>
<?php $counter++ ?>
#endforeach
</div>
<!-- /preview -->
my route
Route::post('unit/API/simpan/{id}', 'partner\UnitController#simpanGambar');
my controller
public function simpanGambar($id)
{
$gambar = Gambar::find($id);
$gambar->delete();
}
you can try this
Route::post('unit/API/simpan', 'partner\UnitController#simpanGambar');
and
public function simpanGambar(Request $request)
{
$gambar = Gambar::find($request->id);
$gambar->delete();
}
or in ajax
$.ajax({
type: 'POST',
url: '{{url("unit/API/simpan")}}' +'/'+ id, <---------- pass id here

How to save the content of a textarea using Ckeditor and CodeIgniter?

I'm using Codeigniter with Ckeditor. My problem is that when I submit the content, the data from the textarea is not stored in the database. But when I tried it again it finally did. So the situation is like I have to double click submit button to save it.
I stored the downloaded Ckeditor on a folder named ./Assests/Ckeditor(Sorry for the wrong spelling.I'll fix this later.)
Here's my form in my view folder:
ask_view.php:
<form id="form" enctype="multipart/data" method="post" onsubmit="createTextSnippet();">
<div class="form-group">
<label for="exampleInputEmail1">Title</label>
<input type="text" name ="title" class="form-control" id="title" placeholder="Title" required >
</div>
<input type="hidden" name="hidden_snippet" id="hidden_snippet" value="" />
<div class="form-group">
<label for="exampleInputEmail1">Editor</label>
<textarea name ="text" class="form-control" id="text" rows="3" placeholder="Textarea" required></textarea>
</div>
<input type="submit" class="btn " name="submit" value ="Submit" style="width: 100%;background: #f4a950;color:#161b21;">
</form>
<script src="<?php echo base_url('assests/js/editor.js')?>"></script>
<script type="text/javascript">
CKEDITOR.replace('text' ,{
filebrowserBrowseUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=2&editor=ckeditor&fldr=')?>',
filebrowserUploadUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=2&editor=ckeditor&fldr=')?>',
filebrowserImageBrowseUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=1&editor=ckeditor&fldr=')?>'
}
);
</script>
<script type="text/javascript">
//code used to save content in textarea as plain text
function createTextSnippet() {
var html=CKEDITOR.instances.text.getSnapshot();
var dom=document.createElement("DIV");
dom.innerHTML=html;
var plain_text=(dom.textContent || dom.innerText);
var snippet=plain_text.substr(0,500);
document.getElementById("hidden_snippet").value=snippet;
//return true, ok to submit the form
return true;
}
</script>
<script type="text/javascript">
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/knowmore2/index.php/ask_controller/book_add',
data: $('form').serialize(),
success: function (data) {
console.log(JSON.parse(data));
}
});
});
</script>
Ask_model.php:
public function book_add($data)
{
$query=$this->db->insert('article', $data);
return $query;
}
Ask_controller.php:
public function book_add(){
$data = $_POST;
$details = array();
$details['title'] = $data['title'];
$details['content'] = $data['text'];
$details['snippet'] = $data['hidden_snippet'];
$details['createdDate']=date('Y-m-d H:i:s');
$result=$this->ask_model->book_add($details);
echo json_encode($details);
}
The content with html tags should be save in a column named content in the database, but it didn't save in the first click. It only saves on the second one,but the other data are saved in the first like the title, etc. So I get 2 rows of data, one without the content and the other with one.
Database:

correctly sending form by ajax

I'm trying to send a form content to current(or another) php file for processing, but I don't know how be sure that my codes works!
<a href="#" class="eb" date-uid="<?php echo $value[0]; ?>" data-toggle="modal" data-target=".bs-example-modal-lg">
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body">
<H2>Edit contact</H2>
<form name="editform" method="post">
<input type="name" name="ename" placeholder="name" required /></br></br>
<input type="tel" name="etel" placeholder="phone number" required /></br></br>
<input type="text" name="edes" placeholder="description" required /></br></br>
<input type="submit" class="esub" name="esub" value="Save" />
</form>
<script>
$(document).ready(
function () {
$(".esub").click(
function () {
var uid = $(".eb").attr("data-id");
var ename = document.getElementByName("ename");
var etel = document.getElementByName("etel");
var edes = document.getElementByName("edes");
ajax({
url: 'uedit.php',
type: 'POST',
data: {
owner: uid,
name: ename,
tel: etel,
description: edes
},
success: function (result) {
return result;
}
});
}
);
}
);
</script>
So is my code right? How could I be sure that my codes run correctly?
remove this line from your jquery code
var uid=$(".eb").attr("data-id");
becouse there is no element having class="eb"
You have a couple errors in your code. Try this:
<script>
$( document ).ready(function() {
$(".esub").click(function(){
var uid=$(".eb").attr("data-id");
var ename=getElementByName("ename");
var etel=getElementByName("etel");
var edes=getElementByName("edes");
ajax({
url:'uedit.php',
type:'POST',
data:({
owner:uid,
name:ename,
tel:etel,
description:edes
}),
success:function(result){
return result;
}
});
});
});
</script>

Upload data and image base 64 to rest server as truncated

I'm using advanced rest console of chrome and i'm sending a rest request to a server that saves an image to database.
below the header data and the body of the request:
Header:
Content-Type: image/jpg; charset=UTF-8
Body:
device_id=1442045686166&id_utente=1&id_attivita=-1&id_prodotto=115&file=/9j/4AAQSkZJRgABAQAAAQABAAD/...
the server, not mine, it all comes back ok but here is the result
image returned
The other images were uploaded from Android application that sends requests to the same server!
The server is a java web application deployed on jboss application server.
This is the html part of retrive image:
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<label for="exampleInputEmail1">Immagine</label>
</div>
<div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
<div class="thumbnail">
<i ng-hide="imageSrc">Nessuna immagine selezionata</i>
<img ng-hide="!imageSrc" ng-src="{{imageSrc}}" on-error-src="images/noimg.png" spinner-on-load/>
<div class="caption">
<div class="form-group">
<input type="file" id="imageInputFile" name="imageInputFile" ng-model="imageInputFile" ng-change="uploadFile(this)" ng-file-select="onFileSelect($files)" base-sixty-four-input maxsize="500" accept="image/*">
<p class="help-block">Scegli un'immagine in locale.</p>
</div>
</div>
</div>
</div>
</div>
</div>
And this is the angularjs code:
$scope.uploadImage = function (id_prodotto) {
trace("uploadImage, inizio");
var img64 = $scope.imageSrc.replace(/^data:image\/(png|jpeg);base64,/, "");
$scope.bodyRawImg =
'device_id=' + $scope.key +
'&id_utente=' + $scope.BeanUtente[0].id_utente +
'&id_attivita=' + $scope.BeanUtente[0].id_attivita +
'&id_prodotto=' + id_prodotto +
'&file=' + img64;
trace("uploadImage, $scope.bodyRawImg " + $scope.bodyRawImg);
$http({
method: 'POST',
url: ($location.absUrl().split("/easyMenu/"))[0] + '/app/file/uploadFoto',
async: false,
processData: false,
headers: {
'Content-Type': 'image/jpg'
},
data: $scope.bodyRawImg,
})
.success(function (data, status, headers, config) { // success
trace("uploadImage, success");
$scope.result = (data || []);
trace("uploadImage response: " + JSON.stringify($scope.result));
})
.error(function (data, status, headers, config) { // error
trace("uploadImage, error");
});
$scope.cambioImmagine = false;

Adding records to a drop down menu without form refresh

I want to add records to a drop down menu without form refresh. I'm using codeigniter and bootstrap
Here is the Bootstrap Modal :
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
<h4 id="myLargeModalLabel" class="modal-title">Add Record</h4>
</div>
<div class="modal-body">
<form class="sky-form" id="sky-inchidere" method="post" accept-charset="utf-8" action="">
<dl class="dl-horizontal">
<dt>Name<span class="color-red">*</span></dt>
<dd>
<section>
<label class="input">
<i class="icon-append fa fa-inbox"></i>
<input type="text" value="" name="name" required>
<b class="tooltip tooltip-bottom-right">Add New Record</b>
</label>
</section>
</dd>
</dl>
<hr>
<button type="submit" class="btn-u" style="float:right; margin-top:-5px;">Submit</button>
</form>
</div>
</div>
</div>
Ajax script :
$(document).ready(function(){
$("#sky-inchidere").submit(function(e){
e.preventDefault();
var tdata= $("#sky-inchidere").serializeArray();
$.ajax({
type: "POST",
url: 'http://localhost/new/oportunitati/add',
data: tdata,
success:function(tdata)
{
alert('SUCCESS!!');
},
error: function (XHR, status, response) {
alert('fail');
}
});
});
});
CI Controller ( i have added the modal code here for test )
public function add() {
$tdata = array( name=> $this->input->post(name),
);
$this->db->insert('table',$tdata);
}
When i use this code i get "fail" error message.
Thanks for your time.
how yo debug:
1. Print your 'tdata' and see what happen;
2. Something wrong here: $this->input->post('name');
Try to use:
$tdata = array(
'name' => $this->input->post('name')
);
I manage to find the problem and correct it. (typo on the table name)
Now I have come across a different problem. In the ajax success I cant refresh the chosen dropdown records i have tried :
success:function(tdata)
{
// close the modal
$('#myModal').modal('hide');
// update dropdown ??
$('.chosen-select').trigger('liszt:updated');
$('#field-beneficiar_p').trigger('chosen:updated');
$('#field-beneficiar_p').trigger('liszt:updated');
},
Any help in how i can refresh the records to see the last added item will be appreciated. I'm using chosen plugin.
from controller send data in json_encode
then in js function
$.ajax({
type: "POST",
url: "<?php echo base_url('login/get_time'); ?>",
data: {"consltant_name": consltant_name, "time": time},
success: function(data) {
var data = JSON.parse(data);
var options = '';
options = options + '<option value="">Please Select One</option>'
$.each(data, function(i, item) {
options = options + '<option value="' + item + '">' + item + '</option>'
});
selectbox.html(options);
}});

Resources