No way to pass data using form with Uploadify - javascript

sorry if I am being redundant but I've tried every single example I found here and on google :D
What I am trying to do is on the upload of image, what was typed on inputbox will be send along to the uplodify.php where my insert is. My problem is, name of picture has being saved to the mysql but what was typed on the textfield dont.
Would you guys let me know what is going on?
This is the part of my code
'multi' : true,
'auto' : false,
'onUploadStart' : function(file) {
$("#file_upload").uploadify('settings', 'formData', {'galeria': $('#galeria').val()});
},
<form id="form1" name="form1" action="">
<p>
<input type="file" id="file_upload" name="file_upload" />
<br>
<br>
Galeria<br>
<label>
<input type="text" name="galeria" id="galeria">
uplodify.php
$galeria = $_POST['galeria'];
$regiao = $_POST['regiao'];
if (!empty($_FILES)) {
$img = $_FILES['Filedata']['name'];
$ext = substr($img, -4);
$img = md5($img).date("dmYHis").$ext;
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $img;
$adicionar = mysql_query ("INSERT INTO imagens (foto, galeria, regiao) VALUES('$img','$galeria','$regiao')");
// $fileTypes = str_replace('*.','',$_REQUEST['fileext']);
// $fileTypes = str_replace(';','|',$fileTypes);
// $typesArray = split('\|',$fileTypes);
// $fileParts = pathinfo($_FILES['Filedata']['name']);
// if (in_array($fileParts['extension'],$typesArray)) {
// Uncomment the following line if you want to make the directory if it doesn't exist
// mkdir(str_replace('//','/',$targetPath), 0755, true);
move_uploaded_file($tempFile,$targetFile);
echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);
// } else {
// echo 'Invalid file type.';
// }
}

Try changing your onUploadStart method to extend the uploadify formData property like this:
onUploadStart: function ( file ) {
var $fileUpload = $('#file_upload')
, formData = $fileUpload.uploadify('settings', 'formData')
, newFormData = $.extend({}, formData, { galeria: $('#galeria').val() });
$fileUpload.uploadify('settings', 'formData', newFormData);
}

I finally managed to made it work
This is the code I used
$('#file_upload').attr('file_upload', response).show();
$.post("insert2.php",{name: fileObj.name, galeria: $("#galeria").val(), regiao: $("#regiao").val()}, function(info) {
alert(info); // alert UPLOADED FILE NAME
});
}
});
Now I have a different problem lol it always show right...
Since the code to save the file on dabase is on insert2.php and the code to rename the picture inside the uploadify.php. How can I save the new name on the database instead the name of file I uploaded?
Another question.... is that a way to generate a thumbnail based on those pictures on database?

Related

how to create window.location response in ajax

For creating a .zip file for checked items with selectbox, i need a response back from the php that leads to the path the .zip file is stored.
This is my ajax call:
// AJAX for Checkbox download
$(document).on('click' , '.cb_down' , function() {
var checkboxes_down = [];
$('.rafcheckbox').each(function() {
if(this.checked) {
checkboxes_down.push($(this).val());
}
});
checkboxes_down = checkboxes_down.toString();
$.ajax({
url:"",
method:"POST",
data:{ checkboxes_down:checkboxes_down },
success:function(response){
window.location = response; // this should lead me to the zip file
}
//.........
My php:
// Multiple download (checkboxes)
if(isset($_POST["checkboxes_down"])) {
// create a tmp folder for the zip file
$tmpfolder = $MainFolderName.'/tmpzip';
if (!is_dir($tmpfolder)) {
mkdir($tmpfolder, 0755, true);
}
$checkboxfiles = explode("," , $_POST["checkboxes_down"]);
$filename = "archive.zip";
$filepath = $tmpfolder."/";
foreach($checkboxfiles as $checkboxfile) {
Zip($checkboxfile, $tmpfolder."/archive.zip"); // Zip is a function that creates the .zip file
}
// header come here
echo $filepath . $filename; // the path to the .zip file
exit;
The .zip file is successful created. I checked it.
The problem is: i do not get the response back from the php script.
So i can not download the .zip file.
What i am doing wrong?
! I changed the echo to 'zip file is created' but even that echo i do not receive as response back

Store canvas image to mysql using path location

I'm trying to save my canvas image (generated by the user in the template) in my database. I've been through a lot of sources here, majority I've combined everything on it and got pretty much confused.
Steps that I'm trying to make:
Html form where provides different choices asked from the user (done)
Each time the user selects his/her choice, beside of it is the canvas that displays the image. (done)
A button that displays the summary of his choices and the canvas image generated through modal (done)
A button to Submit his order with the image in database using php and mysql No error! But it doesn't store my image
I don't need to download it, i just want it to directly store in my database once submitted
So where I'm stuck is in the STEP 4
I'll give a summary choice on my codes: (it works fine in my file, just giving you the outcome idea)
/*This retrieves my data my JS w/c is same file with my HTML: */
$('#review').click(function () {
$('#shape').html($('input[name="shape_design"]:checked').val());
$('#color').html($('input[name="color_design"]:checked').val());
//in this part, i am getting the image displayed in the canvas based on the user's choice
var canvasSource = document.getElementById('myCanvas');
var contextSource = canvasSource.getContext('2d');
var canvasShow = document.getElementById('show_canvas');
var contextShow = canvasShow.getContext('2d');
var image = contextSource.getImageData(0, 0, canvasSource.width, canvasSource.height);
contextShow.putImageData(image, 0, 0); });
});
$(function () { //this function converts the canvas to image, so it is now called as "Show Canvas" , it display well in my modal... not sure if its the right code
$("#submitBtn").bind("click", function () {
var base64 = $('#myCanvas')[0].toDataURL();
$("#show_canvas").attr("src", base64);
$("#show_canvas").show();
});
});
//After reviewing it, this part will perform to store it in the database.. which is quite I'm confused
$('#submitOrder').click(function(confirm){
swal({ //sweetalert style
title: "ORDER SENT", },
function(submit){
setTimeout(function(){
$('#showchoices').submit(); }, 500); //"showchoices" is the name of the Html form, it will proceed to ordersent.php
});
});
For my php which I'm not sure what I'm doing.
Ordersent.php
<? php
$shape_design = $_POST['shape_design'];
$color_design = $_POST['color_design'];
$upload_dir = "upload/"; //what does this do?
$myCanvas = $_POST['myCanvas']; //myCanvas is the name and id in my form
$myCanvas = str_replace('data:image/png;base64,', '', $myCanvas);
$myCanvas = str_replace(' ', '+', $myCanvas);
$data = base64_decode($myCanvas);
$file = $upload_dir."image_name.png";
$success = file_put_contents($file, $data);
$dbc = #mysql_connect('localhost' , 'root', '');
#mysql_select_db('order_tbl', $dbc);
$query1 = "INSERT INTO choices_tbl VALUES (NULL,'$shape_design','$color_design', '$myCanvas')";
if(#mysql_query($query1,$dbc))
{ Header("Location: /home.php"); }
else { print 'error!! '.mysql_error().''; }
?>
I tried following the instructions most of the tutorial, but it doesn't work on me.
I wanted to save it in my database using PATH , my my data type in my tables are
order_tbl
designID INT(6) NOT NULL ,
shape_design VARCHAR(20) ,
color_design VARCHAR(20) ,
myCanvas VARCHAR(150) ,
am I missing an attribute?
thanks for the help in advance! Thanks for bearing with me.

Uploading Zip File To Server With AJAX

I have a php file which takes a zip file and unpacks it then places it at the desired path on my server.
It works great with a typical form that calls on the php file in the action. I am trying to make this work with AJAX but I have tried every piece of code I can find without any luck.
Is there something here I am missing? Surely this can be done?
Form for uploading the zip file,
<div id="response"></div>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" id="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" onClick="uploadZip()" />
</form>
Current JS - I get no errors, the page actually reloads with my current script..
<script>
function uploadZip() {
formdata = new FormData();
if (formdata) {
$('.main-content').html('<img src="LoaderIcon.gif" />');
$.ajax({
url: "assets/upload-plugin.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res){
document.getElementById("response").innerHTML = res;
}
});
}
}
</script>
php script which handles uploading the zip and unzipping it before placing it on the server.
function rmdir_recursive($dir) {
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
else unlink("$dir/$file");
}
rmdir($dir);
}
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
/* PHP current path */
$path = '../plugins/'; // absolute path to the directory where zipper.php is in
$filenoext = basename ($filename, '.zip'); // absolute path to the directory where zipper.php is in (lowercase)
$filenoext = basename ($filenoext, '.ZIP'); // absolute path to the directory where zipper.php is in (when uppercase)
$targetdir = $path . $filenoext; // target directory
$targetzip = $path . $filename; // target zip file
/* create directory if not exists', otherwise overwrite */
/* target directory is same as filename without extension */
if (is_dir($targetdir)) rmdir_recursive ( $targetdir);
mkdir($targetdir, 0777);
/* here it is really happening */
if(move_uploaded_file($source, $targetzip)) {
$zip = new ZipArchive();
$x = $zip->open($targetzip); // open the zip file to extract
if ($x === true) {
$zip->extractTo($targetdir); // place in the directory with same name
$zip->close();
unlink($targetzip);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
This php function works great as long as I do this with the form action. So I am sure my problem exist in the AJAX function.
Thanks for any help you can provide.
formdata = new FormData();
You've created a FormData object but you never put any data into it.
The easiest approach is to specify the form:
formdata = new FormData(document.forms[0]);
You also need to stop the submit button from actually submitting the form so that the JS can do something.
A cleaner approach would be to:
Stop using intrinsic event attributes
Use the submit handler for the form
Get the form from the event
<input type="submit" name="submit" value="Upload" onClick="uploadZip()" />
Becomes:
<input type="submit" name="submit" value="Upload">
function uploadZip() {
formdata = new FormData();
becomes:
function uploadZip(event) {
var formdata = new FormData(this);
// Rest of function
event.preventDefault();
}
and you add:
jQuery("form").on("submit", uploadZip);

Output image to browser before saving it to the folder

I've created a functionality on my website where user's can change the background image via upload. The procedure is following:
User goes to settings page and selects an image file to be uploaded. After selecting image, the browser will output it so that user can preview
it before actually saving it's file to in to the folder and filepath in to the database. After that, if user is happy with the result, he can save it to the
folder by pressing "Upload Background Image" button.
All of the above is handled with AJAX.
I am having trouble to just output the image to the browser without actually saving it twice, first into tests folder and after that into backgrounds folder.
I'm using CodeIgniter as my backend framework and jQuery for my AJAX requests.
Here are my methods for outputting (testing) and saving the image:
public function test_image()
{
if($this->input->is_ajax_request())
{
// This part of code needs to be replaced to only just output the image (return it as a JSON), not actually saving it to another a folder
$ext = pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
$new_img_name = random_string('unique'). "." . $ext;
$config['upload_path'] = './public/images/uploads/tests';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1000000';
$config['max_width'] = '2000';
$config['max_height'] = '1600';
$config['file_name'] = $new_img_name;
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$this->output->set_content_type('application_json');
$this->output->set_output(json_encode(array('image_errors' => $this->upload->display_errors('<p class="text-center">','</p>'))));
return false;
} else {
$this->output->set_content_type('application_json');
$this->output->set_output(json_encode(array('userfile' => $new_img_name)));
}
} else {
echo "Not an ajax request";
}
}
// This method works properly
public function upload_background_image()
{
if (isset($_POST))
{
$ext = pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
$new_img_name = random_string('unique'). "." . $ext;
$config['upload_path'] = './public/images/uploads/backgrounds';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1000000';
$config['max_width'] = '2000';
$config['max_height'] = '1600';
$config['file_name'] = $new_img_name;
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$this->output->set_content_type('application_json');
$this->output->set_output(json_encode(array('image_errors' => $this->upload->display_errors('<p class="text-center">','</p>'))));
return false;
} else {
$this->load->model('user_model');
$user_id = $this->session->userdata('user_id');
$upload_photo = $this->user_model->updateUserInfo($user_id, ['body_background_url' => $new_img_name]);
if ($upload_photo === true) {
$this->session->set_userdata(['body_background_url' => $new_img_name]);
redirect(base_url());
}
}
}
}
And here's my AJAX:
$("#bg-cover-file").change(function(e) {
e.preventDefault();
var form = $(this).closest('form');
form.ajaxSubmit({
dataType: 'json',
beforeSubmit: function() {
},
success: function(response) {
if(response.userfile) {
// Output the image
$('.test-image').attr('src', response.userfile);
$('span.file-input').hide();
// Change the form action attribute
var new_path = 'uploads/upload_background_image';
form.attr('action', new_path);
} else {
$('#error-modal').modal('show');
$("#error-body").html(response.image_errors);
return false;
}
}
});
return false;
});
--Working Demo--
I have put comments in this demo to explain what the steps are so please read them.
If you don't understand anything in this answer please leave a comment below and i will update the answer until you understand line for line. You don't learn from copy/paste so please be sure to understand the answer.
function MyFunction() {
var img=document.getElementById('BackgroundImage');
var Status=document.getElementById('Status');
var savebtn=document.getElementById('savebtn');
/* SetBG will target the body tag of the web page.
You can change this to any element -
var SetBG=document.getElementById('YourID').style;
*/
var SetBG=document.body.style;
//Split the image name
var fileExt=img.value.split('.');
//Use the last array from the split and put to lowercase
var fileformat=fileExt[fileExt.length -1].toLowerCase();
// Check the file extension (Image formats only!)
if((fileformat==='jpg')||(fileformat==='gif')||(fileformat==='png')||(fileformat==='jpeg')) {
if (img.files && img.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
//----Image is ready for preview.
SetBG.background='url('+e.target.result+') no-repeat center center fixed';
/*---- Optional, Set background as cover ---*/
SetBG.backgroundSize="cover";
SetBG.OBackgroundSize="cover";
SetBG.webkitBackgroundSize="cover";
//--Hide Loading Message
Status.style.display="none";
//----- Display (Save/Upload button?)
savebtn.style.display="block";
}
/*-------Reading File....
Display a message or loading gif for large images to be processed?
*/
Status.innerHTML="Loading...";
Status.style.display="block";
savebtn.style.display="none";
reader.readAsDataURL(img.files[0]);
}
}else{
/*----User file input not accepted (File isn't jpg/gif/png/jpeg)
Empty the input element and set the background to default.
*/
Status.innerHTML="Format not accepted";
Status.style.display="block";
savebtn.style.display="none";
SetBG.background='white';
document.getElementById('BackgroundImage').value='';
}
}
#Status{display:none;background:white;color:black;font-size:16pt;}
#savebtn{display:none;}
<div id="Status"></div>
<input type="file" id="BackgroundImage" onchange="MyFunction()"/>
<button id="savebtn" onclick="alert('Now upload the image');">Upload and save</button>
I hope this helps. Happy coding!
This may help you
let assume your browse button's id is bg-cover-file and the id of the image tag where you want to display the image preview_image
$(document).on("change", "#bg-cover-file", function(event)
{
if (this.files && this.files[0])
{
var reader = new FileReader();
reader.onload = function (e)
{
$('#preview_image').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});
function MyFunction() {
var img=document.getElementById('BackgroundImage');
var Status=document.getElementById('Status');
var savebtn=document.getElementById('savebtn');
/* SetBG will target the body tag of the web page.
You can change this to any element -
var SetBG=document.getElementById('YourID').style;
*/
var SetBG=document.body.style;
//Split the image name
var fileExt=img.value.split('.');
//Use the last array from the split and put to lowercase
var fileformat=fileExt[fileExt.length -1].toLowerCase();
// Check the file extension (Image formats only!)
if((fileformat==='jpg')||(fileformat==='gif')||(fileformat==='png')||(fileformat==='jpeg')) {
if (img.files && img.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
//----Image is ready for preview.
SetBG.background='url('+e.target.result+') no-repeat center center fixed';
/*---- Optional, Set background as cover ---*/
SetBG.backgroundSize="cover";
SetBG.OBackgroundSize="cover";
SetBG.webkitBackgroundSize="cover";
//--Hide Loading Message
Status.style.display="none";
//----- Display (Save/Upload button?)
savebtn.style.display="block";
}
/*-------Reading File....
Display a message or loading gif for large images to be processed?
*/
Status.innerHTML="Loading...";
Status.style.display="block";
savebtn.style.display="none";
reader.readAsDataURL(img.files[0]);
}
}else{
/*----User file input not accepted (File isn't jpg/gif/png/jpeg)
Empty the input element and set the background to default.
*/
Status.innerHTML="Format not accepted";
Status.style.display="block";
savebtn.style.display="none";
SetBG.background='white';
document.getElementById('BackgroundImage').value='';
}
}
#Status{display:none;background:white;color:black;font-size:16pt;}
#savebtn{display:none;}
<div id="Status"></div>
<input type="file" id="BackgroundImage" onchange="MyFunction()"/>
<button id="savebtn" onclick="alert('Now upload the image');">Upload and save</button>

Uploadify - onComplete || onAllComplete not work

I know there are already some threads with this question, but none was helpful to me.
I have an image manager and I would like to reload the page with "onComplete" event, but it not work for me.
you can see an example: http://graficnova.com/uploadifytest/imgLoader.php
Everything works successful!!, but u need press f5 key for refresh it :(.
Thx and sorry for my english!
code:
head:
<script type="text/javascript">
$(function() {
$("#fileInput").uploadify({
width : 100,
swf : 'swf/uploadify.swf',
uploader : 'php/uploadify.php',
queueID : 'imgloadList',
oncomplete : function() {
alert('hello world?'); //<- THIS NOT WORK
}
});
});
</script>
php: uploadify.php
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
//$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetPath = 'xxxxx/xxxx/xxxx/xxxx';
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo '1'; //<- return response
} else {
echo 'Invalid file type.'; //<- return response
}
}
Based on the Uploadify docs, there isn't an onComplete event, but there is an 'onUploadComplete' event:
Triggered once for each file when uploading is completed whether it was successful or returned an error. If you want to know if the upload was successful or not, it’s better to use the onUploadSuccess event or onUploadError event.
Might want to give that a try. Or check out onQueueComplete.

Categories