I have a agile File input, im using the model File from addons, at the moment without any extend or modifications.
$f=$this->add('Form');
$modelo = $this->add($this->model);
$f->addField('upload','Upload_test','Upload Test')->setModel($modelo);
$elemento = $this->add('HtmlElement');
$t = $this;
$modelo->addHook('afterSave',function($m) use($t, $elemento)
{
$t->js(true)->univ()->alert('Uploaded!');
$elemento->set('Uploaded');
});
$f->onSubmit(function($f) use($t){
$t->js(true)->univ()->alert(333)->execute();
});
The callback are triggering but, any modifications to the actual html are failed, also any js like the simple alert saying Uploaded. How can I execute some PHP like $elemento->set('Uploaded'); to inform of the recently uploaded file? The JS with the alert also doesnt work :(
Any help would be apreciated
The upload element will have an event "upload" triggered as soon as upload is finished.
https://github.com/atk4/atk4/blob/master/templates/js/ui.atk4_uploader.js#L196
You can fetch data from element's data().
Related
I'm creating a downloads functionality with Laravel. When the user clicks on the 'download' button, I initiate an ajax call to the controller which looks like this -
public function download(Resource $resource) {
// Force download of the file
$file_to_download = 'https://data.domain.com/downloads/' . $resource->file_name;
$temp_file_location = public_path('/tmp_files/' . $resource->file_name);
copy($file_to_download, $temp_file_location);
return response()->download($temp_file_location)->deleteFileAfterSend(true);
}
Chrome's inspector shows that the response gets populated with the contents of the file, but it won't trigger the actual download.
I've been trying to find an answer, but have had no success so far. Would really appreciate your help.
Thank you for your time.
You cannot download a file from an Ajax request because Javascript is unable to save files to your filesystem out of security concerns.
There are a few good packages out there like Jquery File Download
Or you can use a traditional GET request.
I wrote a simple script in plain PHP that uses $_FILES['uploadedfile']['tmp_name'] to fetch a freshly uploaded file and process its contents directly without permanently storing it. The idea is to allow the user to upload a file containing several rows of data that will be automatically parsed and added to a database by the PHP script. There is no need to store the file itself or a reference to it in the database as only the file contents are important. I know of Import CSV to MySQL, but I am trying to keep things clean and easy for the user (and for the time being I am developing with phpDesktop + sqlite so that my application will be portable).
I am now trying to recreate this process within Agile Toolkit but I cannot seem to figure out how. I know that the filestore model must access ['tmp_name'] before it moves/renames the file but I cannot figure out how to poach just this functionality. I tried looking in /lib/Form/Field/Upload.php to see if any of the methods there might be of use, but I am quite new to PHP so these docs are baffling to me. getFilePath() looked promising, but it seems that $_FILES remains empty when I do something like:
$form = $page->add('Form');
$upl = $form->addField('Upload', 'file');
$form->addSubmit();
if ($form->isSubmitted()){
$form->js()->univ()->alert($upl->isUploaded())->execute(); //sends js alert('false')
}
I realize that AJAX cannot be used to post files and I have a feeling this is part of the problem but I am not really sure where to go from here. Any help would sincerely be appreciated.
Thanks.
Agile Toolkit uploads file as soon as it is selected - moves it immediately into filestore and creates database record, so not really what you need.
Anything you write in a plain PHP can also work with Agile Toolkit. You can disable JavaScript in the form by doing this:
$this->add('Form',array('js_widget'=>false));
Such a form would send you a normal POST request.
Ok, I managed to achieve what I wanted by creating a custom extension of Form_Field_Upload and redefining the loadPOST() method within it.
function loadPOST(){
Form_Field::loadPOST();
if($_GET[$this->name.'_upload_action']){
// This is JavaScript upload. We do not want to trigger form submission event
$_POST=array();
}
if($_GET[$this->name.'_upload_action'] || $this->isUploaded()){
if($this->model){
try{
$model=$this->model;
/*Function is identical to parent above this line*/
//process file here and do $model->set('custom_field',$value);
//I am using $this->getFilePath() to analyze the uploaded file
/*Function is identical to parent below this line*/
$model->save();
}catch(Exception $e){
$this->api->logger->logCaughtException($e);
$this->uploadFailed($e->getMessage()); //more user friendly
}
$this->uploadComplete($model->get());
}
}
if($_POST[$this->name.'_token']){
$a=explode(',',$_POST[$this->name.'_token']);$b=array();
foreach($a as $val)if($val)$b[]=$val;
$this->set(join(',',filter_var_array($b,FILTER_VALIDATE_INT)));
}
else $this->set($this->default_value);
}
I sure this is not the most elegant solution but it worked for my purpose anyway.
I am creating image gallery, and first of all, it basically loads thumbnails of images from server with PHP and sets their alt property to the path of the folder, then, what I am trying to do is, when user clicks on one of the images, it should load all images from that folder but it does not. I use jQuery and here is the simplified code. I just need to assign the path to the PHP variable. I tried everything I know but it did not work.
Sending path to the file with PHP
$(document).ready(function(){
$("html").on("click", ".gcube img", function() {
var $path = $(this).attr('alt');
$.post("TESTLOAD.php", { link: $path} );
});
});
TESTLOAD.php file:
<?php
$link = $_POST['link'];
echo $link;
//other stuff that will load images will be here
?>
UPDATE
Ok this is the minified code enough to understand
Code from file which is sending the data(TESTPOST.php):
path = "projects/first/pic.jpg";
$.post("TESTLOAD.php", { link: path} );
And code which should receive data but it dont, or at least it is not echoing anything:
$link = $_POST['link'];
echo '<div id="blah"> ' . json_encode(var_dump($_POST)) . '</div>';
//I was hoping that after I $.post("TESTLOAD.php", { link: path} ); it even echoes out something but it really does nothing
If I just use post in jquery, it echoes nothing so I have to load it again with
$("#output").load("TESTLOAD.php");
But I think if I load it again, the variable is not saved there anymore. Any idea what is wrong?
Okay, I know what was wrong I feel so dumb :D I did not know that I can use jQuery load function and send data at once. Now I am not using post at all, just this one line $("#output").load("TESTLOAD.php", {link:path});
Output: Div where I want to show the loaded data / TESTLOAD.php file which I want to load {link:path} : data which I want to send to the php.
This is how I call the editor:
new nicEditor({
buttonList : ['bold','italic','underline','upload'],
iconsPath:'img/nicedit.png',
uploadURI : 'http://server.com/integracion/files/nicUpload.php'
}).panelInstance(textareaId);
And the .php file exists ( and I the one in the Docs, and I updated the target paths )
/* I want them here http://server.com/integracion/files/uploads/ so... */
define('NICUPLOAD_PATH', './uploads'); // Set the path (relative or absolute) to
// the directory to save image files
define('NICUPLOAD_URI', '/uploads'); // Set the URL (relative or absolute) to
// the directory defined above
But I on response when upload completes (and of corse an alert from nicedit..)
<script>
try {
top.nicUploadButton.statusCb({"error":"Invalid Upload ID"});
} catch(e) { alert(e.message); }
</script>
what am I missing?
-EDIT
I think the problem might be in the php file:
$id = $_POST['APC_UPLOAD_PROGRESS']; /* APC is installed and enabled */
if(empty($id)) {
$id = $_GET['id'];
}
FINAL EDIT:
I have managed to make this work!
Here is an working example:
http://simplestudio.rs/yard/nicedit/
Uploaded images are going to be stored here:
http://simplestudio.rs/yard/nicedit/images/
And here is the whole code, just unpack it and put on your server, mainly I needed to adjust nicEdit.js because it had some issues.
http://simplestudio.rs/yard/nicedit/nicedit.rar
Just make your code with that js file and by looking at my example, it will work :)
Also you need to have php APC installed so that this script can work:
http://php.net/manual/en/apc.installation.php
If you by any mean have some problems I am here to solve it.
I will not delete this example on my server so that everybody who have this issue can freely download it...
The code responsible for image upload is the method uploadFile, it is looking for uploadURI option parameter.
You will need to modify onUploaded event handler to parse your custom response instead of the imgur's one (sample). By default it expects at least {"upload": { "links": {"original": "http://..."}, "image": {"width": "123" } }}.
I'm sorry but I can't help with the FormData() handling server side with PHP.
For more information you can try out the demo page on the nicEdit web site using Firebug or WebInspector to snoop the network requests, and, of course, the source code.
I want to verifie if an image has a valid format with ajax. But I have a problem, how do I set a $_file variable in jQuery?
So I want to "translate" this php code:
$Avatar = $_FILES['Avatar']['name'];
$AvatarTmp = $_FILES['Avatar']['tmp_name'];
To jquery.
And here is (the important part of) the Php script that will be call ($.post):
if(!empty($AvatarTmp))
{
$AvatarSize = getimagesize($AvatarTmp);
if($AvatarSize['mime'] =='image/jpeg')
{
$AvatarSrc = imagecreatefromjpeg($AvatarTmp);
}else
if($AvatarSize['mime'] =='image/png')
{
$AvatarSrc = imagecreatefrompng($AvatarTmp);
}else
if($AvatarSize['mime'] =='image/gif')
{
$AvatarSrc = imagecreatefromgif($AvatarTmp);
}else
{
$Errors[] = "Error006";
$AvatarSrc = false;
}
}
PS: if more code or anything is needed, ask, I'll add it right away.
Unfortunately jQuery (JavaScript) is a wholly different beast from PHP, and so it doesn't have a File object of any type. As #VIPINJAIN mentioned there is the HTML5 file API coming, but it is in its infancy.
You're much better off checking by file extensions (see Check input file for correct format with jquery) or doing the check server-side and outputting an error back from the server if it's in the wrong format.
== EDIT ==
Here is an example of how to use File API, including how to check file type with it, but bear in mind that this will only work in a limited number of browsers:
http://robertnyman.com/2010/12/16/utilizing-the-html5-file-api-to-choose-upload-preview-and-see-progress-for-multiple-files/#highlighter_81142
No you cannot send file in ajax request until and unless you are using html5 file api in mozilla firefox.
alternatively you can do this,
submit the form with file input to an iframe and on the load of the iframe get the contents of body element of iframe using jquery. and check the response of the server.