Laravel 4 Can't route ouput from jQuery to Controller - php

This is a Laravel 4 image manipulation project.
I am going round in circles trying to solve this conundrum, which I am sure has an elementary solution.
The user chooses some images, previews them and then clicks to upload.
The problem is that handleForm's output (the FormData object) does not get routed to the ImageController for the rest of the image handling. On clicking nothing happens. Debugging shows that the FormData object (data in xhr.send(data)) contains the images that the user specified.
The relevant bits: 1 The user clicks to upload.
<input type="button" value="Upload" id="go"/>
In the jQuery the .click event starts handleForm function:
$("#go").on("click", handleForm);
In handleForm the storedFiles array contains the users chosen images after previewing them.
function handleForm(e) {
e.preventDefault();
var data = new FormData();
for(var i=0, len=storedFiles.length; i<len; i++) {
data.append('files', storedFiles[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload', true);
xhr.onload = function(e) {
if(this.status == 200) {
console.log(e.currentTarget.responseText);
alert(e.currentTarget.responseText);
}
}
xhr.send(data);
}
In Routes
Route::post('upload', array(
'as' => 'upload',
'uses' => 'ImageController#upload'
));
In ImageController:
<?php
class ImageController extends BaseController {
public function upload(){
$files = Input::all('files');
$gallery = str_random(12);
foreach ($files as $file) {
$validation = Image::validateImage(array('file'=> $file));
...................
This is the first time I have tried to incorporate jQuery in Laravel and I need some help!

The answer in this case was to change the jQuery to make files into array files[] like:
for(var i=0, len=storedFiles.length; i<len; i++) {
data.append('files[]', storedFiles[i]);
}
I couldn't find this solution anywhere despite hours of searching, it was just a trial and error approach.

Related

Add and delete thumbnail using ajax

I need to create and delete thumbnail image in my yii2 app. I must to have max 5 images and when I was choose files I may to see thumbnails of that images.
I added images in my view with that:
?= $form->field($images, 'imagesFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*','id'=>'gallery-photo-add'])->label(false) ?>
and I can get images in my controller:
$images->imagesFiles = UploadedFile::getInstances($images,'imagesFiles');
How can I see thumbnails? I need to create ajax request? If yes, how I can delete different images? Or add them to my view maybe with some id's.
If you want to see images after choosing them from disk, before submit form, you can preview selected files in view using javascript, eg:
$('#gallery-photo-add').on('change', function() {
var input = $(this)[0];
var images = $('#some-div');
for (var i=0; i<input.files.length; i++) {
if (input.files && input.files[i]) {
var reader = new FileReader();
reader.onloadend = function (e) {
images.append('<img src="'+e.target.result+'" />');
};
reader.readAsDataURL(input.files[i]);
}
}
});

Changing img src with the fileupload value using jquery/php/html

I'm working on a facebook tab that accepts some text and also a picture using an html fileUpload component, the idea is that when the user selects a picture in the fileUpload component, the image they select appears on the page as a way of previewing the picture before uploading it to the server. I tried fectching the image url using val(), but for security reasons, browsers do not give the complete url of a local file. Is there a way to do this using either php or jquery?
Thanks
I believe this is what you're looking for:
function handleFiles(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
preview.appendChild(img);
var reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
}
}
You might also be interested in reading other examples, like this one.
Edit: This method relies on the FileReader API, so it won't work on IE9 as you've pointed out, but I don't think it is possible otherwise.
At the end of the day, do you need IE9 compatibility ? You might find it acceptable to add a functionality that works for all but a few percent of your user base.

How can I avoid <input file> deletes values after selecting files?

I'm working on a web uploader, however, I found something, I do not know if it's a problem. This is what I found:
When I choose files with <input type="file" multiple>, the values ​​of all selected files are stored in a list of files which is within the INPUT. However, when I add more files, the files that I select replace those I selected previously. I think this is a default behavior of this element DOM.
What do I have to do if I want to add more files without deleting my chosen before?
Does anyone know how to do this?
Btw: Sorry for my bad english, It's not my mother language.Thanks.
You can keep track of all FileLists, and loop over each one when sending through ajax: http://jsfiddle.net/46Pk8/. However, keep in mind that you can select (and upload) a file more than once this way. A better method would be to have a visual list, and let the user be able to add/remove files to/from the list.
var files = []; // this will contain FileLists
$("button:first").on("click", function(e) {
$("<input>").prop({
"type": "file",
"multiple": true
}).on("change", function(e) {
files.push(this.files);
}).trigger("click");
});
$("button:last").on("click", function(e) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/echo/html/", true);
var data = new FormData();
$.each(files, function() { // each FileList
$.each(this, function() { // each file inside this list
console.log("appending %s", this.name);
data.append("files", this);
});
});
xhr.onreadystatechange = function(e) {
if(xhr.readyState === 4) {
console.log("done");
}
};
xhr.send(data);
});
As workaround you can insert another input after file choose and hide original one.

Drag and drop files (without live upload) / Sending e.dataTransfer.files through form

I'm working on a new drag-and-drop files plugin, however , unlike all those plugins out there
I don't want it to upload it as it "dropped".
The idea is:
1.The user drags and drops the files.
2.(Some Magic)
3.The user submit the form and only than those files getting uploaded to the server
I tried appending the file's name to the form as an input type=hidden , however I can't do anything with it on the server side (php);
Can I append the file's details to a input type=file field some how so the browser will "think" the file has been selected via regular file input field
My js:
$('#drop-zone').bind('drop', function(e) {
// This variable represents the files that have been dragged
// into the drop area
var files = e.dataTransfer.files;
$('#uploaded-list').show();
// For each file
$.each(files, function(index, file) {
/* What can I do in here?*/
});
});
Thanks.
Maybe you've already solved this, but I figured this out today.
This would not be IE9- compliant (but then again, neither are drag and drop files), but you could store the dataTransfer.files data, and when you're ready to submit, create a FormData from the form and append the files.
var formData = new FormData(html_element_of_form); //not a jq obj!
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
// now post a new XHR request
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload');
xhr.onload = function () {
if (xhr.status === 200) {
console.log('all done: ' + xhr.status);
} else {
console.log('blarrghhhhh...');
}
};
xhr.send(formData);

Php/ajax files uploading: hidden iframe loads more than once

My problem occurs, when I upload images with ajax. Ajax response comes to a hidden iframe, and for debug I echo it (uploaded image name) here and then alert it. So when I upload the first image - there's one alert, as it should be. When I upload the 2nd - I see 2 alerts. The 3rd - 3 alerts. And so on. It means, that my iframe reloads as many times, as the order number of the file being just uploaded.
Interesting, that the names in alerts after each file upload are always the same. For example, 2 times "mySecondImage.jpg", 3 times "myThirdImage.jpg"...
What can be done to solve the problem? Thanks.
// FUNCTION - AJAX FILE UPLOADER
// this function creates new elements, but only in case, when user uploads files
$.fn.fileUploader = function ( $inputName ) {
var $body = $(this);
var $form = $body.parents('form');
var $fileInput = $body.find(':file');
// after file is uploaded, we need the file input to be empty again
var $fileInputEmpty = '<input type="file" name="' + $inputName + '" />';
var $iframe = $('#ajaxResult');
// user submits the form
$form.submit( function() {
// check the result
$iframe.load( function () {
var $response = $iframe.contents().find('body').html();
alert($response); // debug
// add new content image
$output = createUpdateImage( $response, $('[name="imageLinkURL"]').val() );
// add new element
addNewElement( $output );
// success
if ( $response.length ) {
$fileInput.replaceWith( $fileInputEmpty );
$fileInput = $body.find(':file');
}
});
}); // form submit
};
$('.fileUploder').each(function () {
var $inputName = $(this).find(':file').attr('name');
$(this).fileUploader( $inputName );
});
Well, the glitch is fixed!
I slightly rewrote the jQuery function:
...
// user submits the form
$form.submit( function() {
var $response = '';
$iframe.load( function () {
$response = $iframe.contents().find('body').html();
});
// periodically check the result in iframe
var $timer = setInterval( function() {
if ( $response != '' ) {
clearInterval( $timer );
// do all required actions
}
}, 100 );
}); // form submit
...
$form.submit( function() {
$iframe.load( function () {
I think the problem is here. On form submit you add an event "on load". So it called 1 time, then 2 times, etc. Maybe removing the first of these two strings can help (use only load event handler).

Categories