I´m trying to upload my img with ajax, and generate one PDF with barryPDF but my problem it´s i have two different img.
for to do this, i´m sendning in my ajax and form_data one parameter and so i distint my img:
function ajaxDNI2(){
data = new FormData();
let token = $("meta[name='csrf-token']").attr("content");
data.append('file', $("#dni2_cliente")[0].files[0]);
data.append('_token', token);
data.append('dni_atras', 'dni_atras');
$(".dni2").addClass('borderClass');
$.ajax({
url: document.location.origin+'/admin/precontratos/precontratos/dataClientImages',
method: 'POST',
processData: false,
contentType: false,
data: data,
success: function(response){
progressDni2();
$("#imageDniClient").attr('src', response);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
in my controller i have my function:
if($request->hasFile('file')){
if($request->get('dni_delante') == "dni_delante"){
$image = $request->file('file');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('storage/datosCliente');
$image->move($destinationPath, $name);
}
if($request->get('dni_atras') == "dni_atras"){
$image2 = $request->file('file');
$name2 = time().'.'.$image2->getClientOriginalExtension();
$destinationPath2 = public_path('storage/datosCliente');
$image2->move($destinationPath2, $name2);
$pdfName = "documentacion.pdf";
$pathSavePdf = public_path('storage/datosCliente');
$pdf = PDF::loadView('pdf.dni', ['image' => $name, 'image2' => $name2])
->setPaper('a4')
->setOrientation('Portrait')
//->setOption('zoom', 1.2)
->setOption('footer-center', 'EDICIONES GRUPO DELUXE 2013 S.L.U está Inscripta en el Registro Mercantil de Granada al Tomo 1548 Folio 42 Hoja GR46323 Inscrip. 1ª')
->setOption('footer-font-size', 5);
$pdfCreado = $pdf->save($pathSavePdf, true);
}
}
this function upload my img ok, but in my PDF loadView i´m sending my two img. But my problem it´s that return 500 error not defined $name
[2022-04-20 10:53:02] local.ERROR: Undefined variable: name {"userId":60,"exception":"[object] (ErrorException(code: 0): Undefined variable: name at
all my imgs it´s uploaded ok.
Thanks for readme and sorry for my bad english
Related
I am trying to implement cascading drop down box in cakephp 4 using ajax.
I'm getting an 403 error has tried many solutions from google and stack overflow from htaccess till syntax error and logical error can anyone please help trying since long.
Here is my code:
Add.php
<?php echo $this->Form->control('groups',['options' => $groups],array('id'=>'GroupId'));
echo $this->Form->input('user_id',array('id'=>'UsersId'));
?>
<?= $this->Form->button(__('Submit'),array('id'=>'post')) ?>
<?= $this->Form->end() ?>
<?php echo $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js');?>
<script type="text/javascript" >
$(document).ready(function(){
$("#groups").change(function(){
var deptid = $(this).val();
//var path="<?php echo $this->Url->webroot ?>/Users/getbygroup";
$.ajax({
url: '../Users/getbygroup',
type: 'POST',
data: deptid,
dataType: 'json',
cache: false,
contentType: false,
success:function(response){
var len = response.length;
$("#UserId").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#UserId").append("<option value='"+id+"'>"+name+"</option>");
}
}
});
});
});
</script>
Add action in files controller:
public function add()
{
$this->loadModel('Users');
$this->loadModel('Groups');
$this->set('groups', $this->Groups->find('list'));
$result = $this->Users->find('all'); // returns query object
$data = $result->toArray(); // converts query object to key value array
$file = $this->Files->newEmptyEntity();
if ($this->request->is('post')) {
$file = $this->Files->patchEntity($file, $this->request->getData());
if ($this->Files->save($file)) {
$this->Flash->success(__('The file has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The file could not be saved. Please, try again.'));
}
$this->set(compact('file'));
}
getbygroup function in users controller:
public function getbygroup() {
$fname= $this->request->getData('deptid');
$this->viewbuilder()->layout = 'ajax';
$users = $this->Users->find('list', array(
'conditions' => array('Users.group_id' => $fname),
'recursive' => -1));
$this->set('users', $users);
}
I have trying to filter record form database in cakephp. I am using ajax post method to fetch details on same page.But error is missing view file .Here is my controller .
public function userfunddetails(){
$this->autoLayout = false;
$userid = $this->request->data('userid');
$startdate = $this->request->data('startdate');
$startdate = date('Y-m-d', strtotime($startdate));
$enddate = $this->request->data('enddate');
$enddate = date('Y-m-d', strtotime($enddate));
$conditions = array(
array('Recharge.add_date >= ' => $startdate, 'Recharge.add_date <=' => $enddate),
'Recharge.user_id =' => $userid
);
$data = $this->Recharge->find('all',array('conditions'=>$conditions));
$this->set('data', $data);
}
And here is my ajax code . Same thing working on with other function.
I do not know what happen .But same code working for other module.
<script>
$(document).ready(function(){
$('#frm_rechargeHistory_process').submit(function(){
var userid = $("#userid").val();
var startdate = $("#startdate").val();
//alert(startdate);
// var startdate = new Date($('#startdate').val());
//var startdate = $("#startdate").datepicker({ dateFormat: 'yyyy-mm-dd' }).val();
// var enddate = $("#enddate").val(); // Call ajax for pass data to other place
//var enddate = new Date($('#enddate').val());
var enddate = $("#enddate").datepicker({ dateFormat: 'yyyy-mm-dd' }).val();
// alert(enddate);
var dataString = 'userid='+ userid + '&startdate='+ startdate + '&enddate='+ enddate;
if(userid==''||startdate==''||enddate=='')
{
alert("Please Fill All Fields");
}else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "userfunddetails",
data: dataString,
cache: false,
success: function(result){
//alert(result);
$('#txtHint').html(result);
}
});
}
return false;
});
});
</script>
Please check, If it is helpful for you.
In this case,there are two options:
First, you can create the ctp file here: YOURCONROLLER/userfunddetails.ctp and use the $data array.
OR
Second you can put json_encode() in your controller function like below and put die() at the end of function.
<?php echo json_encode(array('data' => $data)); die; ?>
You can found the $data array in your jquery response.
Your ajax call looks for the URL "userHistorydetails" while your function is named "userfunddetails".
Also, shouldn't you use "/controller/userfunddetails" as URL?
I know you guys may have already answered loads of questions like this but I really need some help in my situation.
I couldn't find any answer that suits me.
I have 2 dropdown lists in a form (form id MapInitForm) :
Zone : a list of my zones (id : zoneSelect), already populated
Territory : a list of my territories (id : territorySelect)
I do have a zone_id in my Territories table.
So when I select one Zone, I need to get all associated Territories. And when I select one territory, I'll need to do some PHP stuff;
EDITED thanks to Mark's answer.
$('#MapInitForm #zoneSelect').change(function(){
var zone_id = $(this).val();
var zone_id = $(this).val();
var targeturl = $(this).attr('rel') + '?id=' + zone_id;
$.ajax({
type: 'get',
url: targeturl,
beforeSend: function(xhr) {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
},
success: function(response) {
if (response.content) {
$('#territorySelect').html(response.content);
}
else {
console.log(response.content);
}
},
error: function(e) {
alert("An error occurred: " + e.responseText.message);
console.log(e);
}
});
});
In my controller :
public function zone_territories_ajax() {
$this->request->onlyAllow('ajax');
$id = $this->request->query('id');
if (!$id) {
throw new NotFoundException();
}
$this->loadModel('Territory');
$data = $this->paginate('Territory', array('Territory.zone_id =' => $id));
// $data = $this->Territory->find('all', array('condition' => array('Territory.zone_id =' => $id)));
$this->set('zoneTerritories', $data);
}
In my view :
$url = $this->Html->url(array('controller' => 'zones', 'action' => 'zone_territories_ajax'));
echo $this->Form->create('Map');
echo $this->Form->input('zone_id', array(
'options' => $zones,
'empty' => '--- Select one ---',
'id' => 'zoneSelect',
'rel' => $url
));
echo $this->Form->input('zone_territory_id', array(
'empty' => '--- Select one zone ---',
'id' => 'territorySelect',
));
echo $this->Form->end();
And finally in my zone_territories_ajax.ctp :
if (!empty($zoneTerritories)) {
$k = 0;
foreach($zoneTerritories as $zoneTerritory):
echo '<option value="' . $k . '">' . $zoneTerritory['Territory']['name'] . '</option>';
$k++;
endforeach;
}
else {
echo '<option value="0">' . __('noOptionAvailable') . '</option>';
}
In my console, I'm getting undefined for console.log(response.content);
But I'm getting the correct values for the selected zone (I see those in my console again) but nothing happens on the second dropdown list.
What did I do wrong ?
You are lucky, just a while back I wrote something about AJAX and CakePHP:
http://www.dereuromark.de/2014/01/09/ajax-and-cakephp
And in particular, you can see a full blown example of exactly that functionality here:
http://sandbox.dereuromark.de/sandbox/ajax_examples/chained_dropdowns
The code is linked at the bottom - see github
Basically:
$('#source').change(function() {
var selectedValue = $(this).val();
var targeturl = $(this).attr('rel') + '?id=' + selectedValue;
$.ajax({
type: 'get',
url: targeturl,
beforeSend: function(xhr) {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
},
success: function(response) {
if (response.content) {
$('#target').html(response.content);
}
},
error: function(e) {
alert("An error occurred: " + e.responseText.message);
console.log(e);
}
});
});
I've been able to save canvas image data using .ajax() and php but not in cake. The way I've done it is like the following. I have a javascript that runs when a user clicks "submit" button in a form after making a canvas drawing:
var formdata = $("form").serialize();
var data = document.getElementById("canvasElement").toDataURL();
formdata += "&img=" + data;
$.ajax({
type: "POST",
url: "process.php",
data: formdata,
success: function() {
$('body').prepend('<div class="alert">Your bit of data was successfully saved.</div');
$('.alert').delay(2000).slideUp('slow');
},
error:function (xhr, ajaxOptions, thrownError){
alert("Error Status: " + xhr.status + " Thrown Errors: "+thrownError);
}
Then process.php handles the image data and saves it to a file. Here's the salient part:
$img = $_POST['img'];
// remove header information that's sent with the encoded data
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = "images/" . uniqid() . '.png';
This all works as I hoped. How can I do this in a cakephp framework? I've read that in place of a regular cake form submit, you can use the Js helper for an ajax submit like this:
echo $this->Js->submit('Save');
Are there arguments I could pass into the submit function that would let me save the image data? Is there a better way?
I've gotten it to work, but I'm not completely sure I understand why and I'd like to understand the best way to do this in cake. I added a command for the Js helper to put scripts in the head with this: echo $this->Js->writeBuffer(array('cache'=>TRUE));
Other than that, I don't think I changed anything. However, my redirect in my save function in the controller doesn't do anything. I'm only able to achieve a redirect by putting it in the javascript as below.
<?php
// This is my form for saving the drawing
echo $this->Form->create('Drawing');
echo $this->Js->submit('Save', array(
'before'=>$this->Js->get('#sending')->effect('fadeIn')
));
echo $this->Form->end();
?>
public function save() {
// This is my save function in the controller
if ($this->request->is('post')) {
$img = $this->request->data['img'];
// remove header information that's sent with the encoded data
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = uniqid() . '.png';
$filepath = 'drawings/';
$success = file_put_contents($filepath . $file, $data);
print $success ? $file : 'Unable to save the file.';
$arr = array( 'Drawing' => array ( 'filename' => $file, 'filepath' => '/images'));
if ($this->Drawing->save($arr)) {
$this->Session->setFlash('Your drawing has been saved!');
// this redirect doesn't work (and I do have an index page and function)
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your post.');
}
}
}
Javascript is here:
var data = document.getElementById("canvasElement").toDataURL();
formdata = "img=" + data;
$.ajax({
type: "POST",
url: "save",
data: formdata,
success: function() {
window.location.replace("index"); // This redirect works
},
error:function (xhr, ajaxOptions, thrownError){
alert('error in: ' + settings.url + ' \\n'+'error:\\n' + exception);
}
});
}
i am trying to get a response from codeigniter when I send my ajax request from sencha touch/ Ext with
Ext.Ajax.request({//
url: formBase.url, //something like 'http://path.to/mobile/Login/ajax_validateLogin',
success: function(response, opts) {
console.log('Login success!');
console.log('data: ' + response.responseText);
},
failure: function(result){
console.log('Login Error! ');
},
method: 'POST',
params: form.getValues()
});
form = new Ext.form.FormPanel(formBase);
//...
and in codeigniter something like
function ajax_validateLogin() {
$username = $this->input->post('username');
$password = $this->input->post('password');
$data['username'] = 'Arschkarte'; //$username;
if($username == "f"){
$data["success"] = true;
} else {
$data["success"] = false;
$data["errors"]["reason"] = "Login failed. Try again.";
}
$this->load->view('mobile/loginMobile', $data);
}
and the view
<?php
echo 'username: '.$username;
?>
i allways get the Error "Login Failed" and the response of the POST is allways empty (while parameters are send correctly)
any ideas?
THNX!!!