Well I am not able to send form multiple times. The initial part of the code of AjaxForm is working fine whereas the FormData is not working. Instead it send the data in the url without the page like
index.php?photos[]=&username=dfdfdf. The Earlier part is used for image storage and second part is used for user data storage. My requirement is to use single form to send data to different table in database. When the user click submit the data is stored in the data table and the uploaded image also gets updated with that user ID.
Hope You will solve the problem!
<?php
session_start();
include("db.php");
$str = "select * from fileupload order by id DESC";
$res = mysql_query($str);
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.wallform.js"></script>
<script>
$(document).ready(function() {
$('#photoimg').die('click').live('change', function() {
$("#imageform").ajaxForm({
url : 'ajaxImageUpload.php',
target: '#preview',
beforeSubmit:function(){
console.log('ttest');
$("#imageloadstatus").show();
$("#imageloadbutton").hide();
},
success:function(){
console.log('test');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
},
error:function(){
console.log('xtest');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
} }).submit();
});
$(".del-pic").live("click", function(){
var sel1 = $(this).closest('.imgList');
var del_id = $(this).attr('id');
$.post("deleteimage.php", {
del_id : del_id
},
function(data, txtStatus) {
sel1.fadeOut('slow', function()
{
sel1.remove();
});
});
});
$("#uploadTrigger").click(function(){
$("#photoimg").click();
});
$("#upbutton").live("click", function(){
$("#imageform").bind('submit',function(e){
if(window.FormData !== undefined) // for HTML5 browsers
{
var formdata = new FormData(this);
$.post({
url : "insertuser.php",
type : "POST",
data : formdata,
mimeType : "multipart/form-data",
contentType : false,
cache : false,
processData: false,
success: function(data, txtstatus, jqXHR)
{
alert('success');
},
error: function(data, txtstatus, errorthrown)
{
alert('error');
}
});
}
else
{
alert('HTML5 not supporting in your browser');
}
});
});
});
</script>
<style>
#preview
{
color:#cc0000;
font-size:12px;
background: #066;
}
.imgList
{
max-height:100px;
margin-left:10px;
border:1px solid #dedede;
padding:4px;
float:left;
}
.hidden
{
display: none;
}
#uploadTrigger
{
cursor: pointer;
border: 1px solid #333;
padding: 10px;
margin: 5px 5px 5px 5px;
background: #777;
color: #fff;
width:75px;
border-radius: 20px;
font-family:arial;
}
.del-pic
{
background-image:url(../../Krishna/images2/closebox.png);
width:30px;
height:30px;
display:block;
position: absolute;
margin:-10px 0 0 85px;
}
</style>
</head>
<body>
<div>
<div id='preview' style="">
<?
while($row = mysql_fetch_array($res))
{
echo "<div class='imgList'><div class='del-pic' id='".$row['id']."'></div><img src='".$row['filename']."' width='100px' height='100px' ></div>";
}
?>
</div>
<form id="imageform" name="imageform" enctype="multipart/form-data" style="clear:both">
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<div id="uploadTrigger">Add Photo</div>
<input type="file" name="photos[]" id="photoimg" class="hidden" multiple="true" />
<input name="username" type="text" id="username" />
<input type="submit" value="Upload" id="upbutton" />
</div>
</form>
</div>
</body>
</html>
Related
The percentage of progress bar does not work correctly
The correct progress bar does not work and it's 100% fast
But the file has not uploaded yet
Click the submit button
The progress bar is completed quickly
But still the file is being uploaded
I'm interested in understanding the code forms
<?php
$msg = [
"title file"
,"url file"
,"send file"
];
?>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-rtl.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<script src="jquery.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js"></script>
<style>
.del {
border-radius: 100%;
display: inline-block;
font-size: 13px;
height: auto;
margin-right: 4px;
padding: 5px;
}
.box {
height: 41px;
padding-top: 2px;
vertical-align: middle;
}
#uploadurl {
border: 1px solid #ccc;
margin-bottom: 7px;
margin-top: 14px;
padding-top: 11px;
}
</style>
<script>
var template = '<div class="form-group box">' +
'<input type="text" class="col-sm-5 form-control" name="title[]" placeholder="<?=$msg[0]?>">' +
'<input type="text" class="col-sm-6 form-control" name="url[]" placeholder="<?=$msg[1]?>">' +
'<i class="fa fa-times" aria-hidden="true"></i>' +
'<div class="progress-bar progress progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div></div>';
$(document).ready(function(){
$('.add').on('click',function (e) {
$("#uploadurl").append(template);
});
$(document).on('click','.del',function (e) {
var del = $(this).closest('.box').index();
$('.box').eq(del).remove();
});
$('#submit').click(function (e) {
e.preventDefault();
$("input[name='url[]']").each(function (index, value){
$('.myprogress').eq(index).css('width', '0');
var url = $(this).val();
var title = $("input[name='title[]']").eq(index).val();
if(title == ""){
title = <?=strtotime(date('Y-m-d h:s:i'))?>;
}else{
title =<?=strtotime(date('Y-m-d h:s:i'))?>+"_"+title;
}
var data = "url="+url+"&title="+title;
$.ajax({
type: 'POST',
url: "upload.php",
data: data,
datatype:"json",
// contentType: "application/x-www-form-urlencoded",
processData: false,
// this part is progress bar
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.myprogress').text(percentComplete + '%');
$('.myprogress').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
success: function (data) {
$('#fileupload').append("<a style='display: block' href='"+data+"'>"+data+"</a>");
}
});
});
});
});
</script>
<div class="container">
<form id="upload-form" method="post">
<div id="uploadurl" class="col-md-12">
<div class="form-group box">
<input type="text" class="col-sm-5 form-control" name="title[]" placeholder="<?=$msg[0]?>">
<input type="text" class="col-sm-6 form-control" name="url[]" placeholder="<?=$msg[1]?>">
<div class="progress-bar progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div>
</div>
</div>
<div style="display: block">
+
<input type="submit" class="btn btn-primary" id="submit" value="<?=$msg[2]?>" name="submit">
</div>
</form>
<div id="fileupload">
</div>
</div>
upload.php
$title = $_POST['title'];
$url = $_POST['url'];
$now = date('Y-m-d h:s:i');
$partition = date('Ym', strtotime($now));
$folder = "file/attach/".$partition."/";
if (!file_exists($folder)) {
$old = umask(0);
mkdir($folder, 0777);
umask($old);
}
$p = pathinfo($url);
$newfile = $folder.$title.".".$p['extension'];
if ( copy($url, $newfile) ) {
echo $newfile;
}else{
echo "false";
}
Click on the link below to view the demo
In the firebug you see, the file is still being uploaded
But the percentage of progress has been 100%.
demo
When I needed a progress bar to add to my file downloads(in my project); I used this code. I have tested this code also. Try the code below; I am quite sure it will serve your purpose:
<!doctype html>
<head>
<title>File Upload Progress Demo</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius:
10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding:
1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px;
}
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>File Upload Progress Demo #1</h1>
<code><input type="file" name="myfile"></code>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedfile"><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js">
</script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
status.html(xhr.responseText);
}
});
})();
</script>
</body>
</html>
My php upload file:
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error in the upload, please try again!";
}
?>
Hope it helps you and serve as a documentation for you...Happy coding
Here is my main html file;
<!DOCTYPE html>
<html lang="en">
<head>
<title>Create Template</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel = "stylesheet"
type = "text/css"
href = "jquery-ui-1.11.4.custom/jquery-ui.css " />
<style type = "text/css">
.dragMe {
width: auto;
height: auto;
/* border: 1px solid blue; */
text-align: center;
background-color: white;
position: absolute;
display:inline-block;
z-index: 100;
}
.dragMeImage {
width: 180px;
height: 55px;
border: 1px solid blue;
text-align: center;
background-color: white;
position: absolute;
z-index: 100;
}
#target {
width: 400px;
height: 600px;
border: 1px solid red;
text-align: center;
position: absolute;
left: 400px;
top: 100px;
z-index: 0;
}
</style>
<script type = "text/javascript"
src = "jquery-1.12.4.min.js">
</script>
<script type = "text/javascript"
src = "jquery-ui-1.11.4.custom/jquery-ui.min.js">
</script>
<script type = "text/javascript" src="ajaxshow.js">
</script>
<script type = "text/javascript">
$(init);
function init(){
//make all drag me elements draggable
$(".dragMe").draggable();
$(".dragMeImage").resizable({
//aspectRatio: 3.2
});
//set target as droppable
$("#target").droppable();
//bind events to target
$("#target").bind("drop", changeTarget);
$("#target").bind("dropout", resetTarget);
} // end init
function changeTarget(event, ui){
$("#target").addClass("ui-state-highlight")
.html("Dropped ")
.append(ui.draggable.text());
} // end changeTarget
function resetTarget(event, ui){
$("#target").removeClass("ui-state-highlight")
.html("Drop on me");
} // end reset
</script>
</head>
<body id="page2">
<form id=form enctype="multipart/form-data" method="post" action="show_images.php">
<input type="submit" value="Continue"/>
</form>
<div id="preview"></div>
<div id="err"></div>
<!-- <h2>Create an Invitation Template to be Sent to the List Owners</h2>
<div class = "dragMe">
<img class = "dragMeImage" src="garbo.png" alt="Garbo Logo" style="width:180px;height:120px;">
</div>
<div class = "dragMe">
<img class = "dragMeImage" src="CA.png" alt="Garbo Logo" style="width:180px;height:55px;">
</div>
<div class = "dragMe">
<img class = "dragMeImage" src="CA1.png" alt="Garbo Logo" style="width:180px;height:55px;">
</div>
<div id = "target">
Drop on this template
</div> -->
</body>
</html>
Here is ajaxshow.js;
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "http://localhost/phpexamples/show_images.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid file')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
});
and here is the PHP file;
<?php
$folder = "uploads/";
if(is_dir($folder)){
if($handle = opendir($folder)){
while(($file=readdir($handle)) != false){
if($file==='.' || $file==='..') continue;
list($width, $height) = getimagesize("uploads/$file");
$h=150/$width*$height;
$aspect = $height / $width;
if ($aspect >= 1) $mode = "vertical";
else $mode = "horizontal";
echo '<div class = "dragMe">';
echo '<img class = "dragMeImage" src="uploads/'.$file.'" width="150" height="$h" alt="">';
echo '</div>';
}
closedir($handle);
}
}
?>
When I load the images in static HTML (commented out) it works fine. When I run the code above it loads the first image in the directory but it's not draggable or resizable. When I take the class ID's out of the echo part of the PHP file. It loads the images OK but of course they are not draggable or resizable. Can anyone help. Many thanks. Neil.
Since you are adding content dynamically after the image has been uploaded, you will need to call .draggable() on the new elements.
I would advise doing this once your AJAX completes:
$.ajax({
url: "http://localhost/phpexamples/show_images.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function() {
$("#err").fadeOut();
},
success: function(data) {
if(data=='invalid file') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
$("#preview").find(".dragMe").draggable();
}
},
error: function(e) {
$("#err").html(e).fadeIn();
}
});
I am using the below code to upload file to the online test server(http://posttestserver.com/post.php) and it is getting successfully uploaded and the code is also working fine as required but the issue is I have to upload the file to an internal PHP server i.e., https://xxxx.xxxx.xxxxx.com/sites/default/files/FileUpload/upload_file.php which is not working for below code while if I remove the ajax,progress bar and script part and run the code only with form tag it can upload the file.
Please help me I cant able to track the issue and I dont have knowledge in PHP.
Also find below the Error log in comment.
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<style>
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
#progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
#bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
#percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>Ajax File Upload Demo</h1>
<form id="myForm" action="http://posttestserver.com/post.php" method="post" enctype="multipart/form-data">
<input type="file" size="60" name="file">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>
<br/>
<div id="message"></div>
<script>
$(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#message").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
</script>
</body>
</html>
Saikat, using ajax to upload file is a pain in the a..
check this out for your referrence
http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
UPDATE CODE BELOW
I found some code that is able to upload an image and display its thumbnail. However, I would like to save the images to a particular folder as well.
What jQuery code or ajax code can I use to save the original image to a folder of my choice?
Here is the live demo: http://jsfiddle.net/dn9Sr/2/
Here is the full code:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<style>
.input-file-row-1:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
.input-file-row-1{
display: inline-block;
margin-top: 25px;
position: relative;
}
#preview_image {
display: none;
width: 90px;
height: 90px;
margin: 2px 0px 0px 5px;
border-radius: 10px;
}
.upload-file-container {
position: relative;
width: 100px;
height: 137px;
overflow: hidden;
background: url(http://i.imgur.com/AeUEdJb.png) top center no-repeat;
float: left;
margin-left: 23px;
}
.upload-file-container-text{
font-family: Arial, sans-serif;
font-size: 12px;
color: #719d2b;
line-height: 17px;
text-align: center;
display: block;
position: absolute;
left: 0;
bottom: 0;
width: 100px;
height: 35px;
}
.upload-file-container-text > span{
border-bottom: 1px solid #719d2b;
cursor: pointer;
}
.one_opacity_0 {
opacity: 0;
height: 0;
width: 1px;
float: left;
}
</style>
<script>
$( document ).ready(function() {
function readURL(input, target) {
if (input.files && input.files[0]) {
var reader = new FileReader();
var image_target = $(target);
reader.onload = function (e) {
image_target.attr('src', e.target.result).show();
};
reader.readAsDataURL(input.files[0]);
}
}
$("#patient_pic").live("change",function(){
readURL(this, "#preview_image")
});
});
</script>
</head>
<body>
<form name="" method="post" action="#" class="feedback-form-1">
<fieldset>
<div class="input-file-row-1">
<div class="upload-file-container">
<img id="preview_image" src="#" alt="" />
<div class="upload-file-container-text">
<div class = 'one_opacity_0'>
<input type="file" id="patient_pic" label = "add" />
</div>
<span> Add Photo </span>
</div>
</div>
</div>
</fieldset>
</form>
</body>
</html>
UPDATE: I think I am on the right track. I am close but I don't know what data to send from the jQuery. I added a php scrit and its getting a call back as success but I am not sending the right var. I think if I just send the right val I can get it.
CODE:
<script>
$( document ).ready(function() {
function readURL(input, target) {
if (input.files && input.files[0]) {
var reader = new FileReader();
var image_target = $(target);
reader.onload = function (e) {
image_target.attr('src', e.target.result).show();
$.ajax({
type:'POST',
url: 'theUpload.php',
data: input.files[0],
success:function(data){
console.log("success");
console.log(data);
alert(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
};
reader.readAsDataURL(input.files[0]);
}
}
$("#patient_pic").live("change",function(){
readURL(this, "#preview_image")
});
});
</script>
Try this one.
Script:
function uploadFile(){
var input = document.getElementById("file");
file = input.files[0];
if(file != undefined){
formData= new FormData();
if(!!file.type.match(/image.*/)){
formData.append("image", file);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
alert('success');
}
});
}else{
alert('Not a valid image!');
}
}else{
alert('Input something!');
}
}
HTML:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<input type="file" id="file" />
<button onclick="uploadFile();">Upload</button>
</body>
</html>
upload.php:
<?php
$dir = "image/";
move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_FILES["image"]["name"]);
?>
John's answer is good but file = input.files[0] doesn't work for me
file = input[0].files[0]
works.
You need a server side language to store the uploaded image to specified folder. PHP is one of them, so I highly recommend to take a look of it.
AJAX is just for executing server side calls without refreshing the page.
I'm trying to upload an image using codeigniter and ajax. I already have the ajax method to insert the field values to the DB, what's the easiest and simplest way to upload my file.
Here's the JQuery custom function:
(function($){
jQuery.fn.ajaxSubmit =
function() {
$(this).submit(function(event) {
event.preventDefault();
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
url: url,
type: "POST",
data: data,
dataType: "html",
success: function(msg) {
$('#main').html(msg);
}
});
return this;
});
};
})(jQuery);
I call it like this:
$(document).ready(function() {
$('#myForm').ajaxSubmit();
});
The function works fine, the data gets inserted in the database and I even have some directories that get created in the model before uploading the image, they are created but the image is not uploaded at all.
I know I need to use a hidden Iframe to do the job, but I dont quite know how to integrate that in my code.
I created custom Ajax File Uploader using CodeIgniter, jQuery and Malsup form plugin. Here is the HTML and Javascript/CSS code. It also support multiple file upload and Progress.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Ajax UP Bar</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('form').submit( function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$(this).ajaxForm({
beforeSend: function() {
status.html();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
});
</script>
</head>
<body>
<form method="post" action="<?php echo base_url('users/upload/'); ?>" enctype="multipart/form-data">
<label for="upload">Select : </label>
<input type="file" name="upload[]" id="upload" multiple="multiple" />
<input type="submit" name="fsubmit" id="fsubmit" value="Upload" />
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
</body>
</html>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
In CodeIgniter Controller :
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Users extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function upload()
{
if (isset($_FILES['upload']['name'])) {
// total files //
$count = count($_FILES['upload']['name']);
// all uploads //
$uploads = $_FILES['upload'];
for ($i = 0; $i < $count; $i++) {
if ($uploads['error'][$i] == 0) {
move_uploaded_file($uploads['tmp_name'][$i], 'storage/' . $uploads['name'][$i]);
echo $uploads['name'][$i] . "\n";
}
}
}
}
}
Hope this helps you. Thanks!!