I want to upload files using PHP but the problem is that I don't know how many files I will upload.
My question is how can I upload files if I use file[]?
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label><input type="file" name="file[]" id="file" />
<br />
<label for="file">Filename:</label><input type="file" name="file[]" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
I will add just File box and I will use JavaScript to create more file input to upload but how to handle them in PHP?
See: $_FILES, Handling file uploads
<?php
if(isset($_FILES['file']['tmp_name']))
{
// Number of uploaded files
$num_files = count($_FILES['file']['tmp_name']);
/** loop through the array of files ***/
for($i=0; $i < $num_files;$i++)
{
// check if there is a file in the array
if(!is_uploaded_file($_FILES['file']['tmp_name'][$i]))
{
$messages[] = 'No file uploaded';
}
else
{
// copy the file to the specified dir
if(#copy($_FILES['file']['tmp_name'][$i],$upload_dir.'/'.$_FILES['file']['name'][$i]))
{
/*** give praise and thanks to the php gods ***/
$messages[] = $_FILES['file']['name'][$i].' uploaded';
}
else
{
/*** an error message ***/
$messages[] = 'Uploading '.$_FILES['file']['name'][$i].' Failed';
}
}
}
}
?>
This is a preferred method of mine. It includes a mysql insert to keep a table on the images uploaded. It also moves the image to the admin image folder and copies the image to the user sites image folder.
<?php
if(isset($_FILES['image']['tmp_name']))
{
$num_files = count($_FILES['image']['tmp_name']);
for($x =0; $x< $num_files;$x++){
$image = $_FILES['image']['name'][$x];
if(!is_uploaded_file($_FILES['image']['tmp_name'][$x]))
{
$messages[] = $image.' No file uploaded."<br>"';
}
if (move_uploaded_file($_FILES["image"]["tmp_name"][$x],"images/". $image)){
$messages[] = $image .' uploaded';
}
copy("images/".$image, '../images/'.$image);
mysql_query("INSERT INTO $table_name VALUES ('NULL','$id','images/$image')");
}
}
?>
<?php /*insert this into the form*/
$count= count($messages); for ($i =0; $i < $count; $i++){echo $messages[$i]."<br>";}
?>
Try this:
if(isset($_FILES['image_file'])) {
$file = $_FILES['image_file'];
for($i = 0; $i < count($file['name']); $i++){
$image = array(
'name' => $file['name'][$i],
'type' => $file['type'][$i],
'size' => $file['size'][$i],
'tmp_name' => $file['tmp_name'][$i],
'error' => $file['error'][$i]
);
// Here is your code to handle one file
}
In your code, just use '$image' instead of '$_FILES' ...
Ajax js
(function(){
var d = document, w = window;
/**
* Get element by id
*/
function get(element){
if (typeof element == "string")
element = d.getElementById(element);
return element;
}
/**
* Attaches event to a dom element
*/
function addEvent(el, type, fn){
if (w.addEventListener){
el.addEventListener(type, fn, false);
} else if (w.attachEvent){
var f = function(){
fn.call(el, w.event);
};
el.attachEvent('on' + type, f)
}
}
/**
* Creates and returns element from html chunk
*/
var toElement = function(){
var div = d.createElement('div');
return function(html){
div.innerHTML = html;
var el = div.childNodes[0];
div.removeChild(el);
return el;
}
}();
function hasClass(ele,cls){
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
if (document.documentElement["getBoundingClientRect"]){
var getOffset = function(el){
var box = el.getBoundingClientRect(),
doc = el.ownerDocument,
body = doc.body,
docElem = doc.documentElement,
// for ie
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
// In Internet Explorer 7 getBoundingClientRect property is treated as physical,
// while others are logical. Make all logical, like in IE8.
zoom = 1;
if (body.getBoundingClientRect) {
var bound = body.getBoundingClientRect();
zoom = (bound.right - bound.left)/body.clientWidth;
}
if (zoom > 1){
clientTop = 0;
clientLeft = 0;
}
var top = box.top/zoom + (window.pageYOffset || docElem && docElem.scrollTop/zoom || body.scrollTop/zoom) - clientTop,
left = box.left/zoom + (window.pageXOffset|| docElem && docElem.scrollLeft/zoom || body.scrollLeft/zoom) - clientLeft;
return {
top: top,
left: left
};
}
} else {
// Get offset adding all offsets
var getOffset = function(el){
if (w.jQuery){
return jQuery(el).offset();
}
var top = 0, left = 0;
do {
top += el.offsetTop || 0;
left += el.offsetLeft || 0;
}
while (el = el.offsetParent);
return {
left: left,
top: top
};
}
}
function getBox(el){
var left, right, top, bottom;
var offset = getOffset(el);
left = offset.left;
top = offset.top;
right = left + el.offsetWidth;
bottom = top + el.offsetHeight;
return {
left: left,
right: right,
top: top,
bottom: bottom
};
}
/**
* Crossbrowser mouse coordinates
*/
function getMouseCoords(e){
if (!e.pageX && e.clientX){
// In Internet Explorer 7 some properties (mouse coordinates) are treated as physical,
// while others are logical (offset).
var zoom = 1;
var body = document.body;
if (body.getBoundingClientRect) {
var bound = body.getBoundingClientRect();
zoom = (bound.right - bound.left)/body.clientWidth;
}
return {
x: e.clientX / zoom + d.body.scrollLeft + d.documentElement.scrollLeft,
y: e.clientY / zoom + d.body.scrollTop + d.documentElement.scrollTop
};
}
return {
x: e.pageX,
y: e.pageY
};
}
/**
* Function generates unique id
*/
var getUID = function(){
var id = 0;
return function(){
return 'ValumsAjaxUpload' + id++;
}
}();
function fileFromPath(file){
return file.replace(/.*(\/|\\)/, "");
}
function getExt(file){
return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : '';
}
// Please use AjaxUpload , Ajax_upload will be removed in the next version
Ajax_upload = AjaxUpload = function(button, options){
if (button.jquery){
// jquery object was passed
button = button[0];
} else if (typeof button == "string" && /^#.*/.test(button)){
button = button.slice(1);
}
button = get(button);
this._input = null;
this._button = button;
this._disabled = false;
this._submitting = false;
// Variable changes to true if the button was clicked
// 3 seconds ago (requred to fix Safari on Mac error)
this._justClicked = false;
this._parentDialog = d.body;
if (window.jQuery && jQuery.ui && jQuery.ui.dialog){
var parentDialog = jQuery(this._button).parents('.ui-dialog');
if (parentDialog.length){
this._parentDialog = parentDialog[0];
}
}
this._settings = {
// Location of the server-side upload script
action: 'upload.php',
// File upload name
name: 'userfile',
// Additional data to send
data: {},
// Submit file as soon as it's selected
autoSubmit: true,
// The type of data that you're expecting back from the server.
// Html and xml are detected automatically.
// Only useful when you are using json data as a response.
// Set to "json" in that case.
responseType: false,
// When user selects a file, useful with autoSubmit disabled
onChange: function(file, extension){},
// Callback to fire before file is uploaded
// You can return false to cancel upload
onSubmit: function(file, extension){},
// Fired when file upload is completed
// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
onComplete: function(file, response) {}
};
// Merge the users options with our defaults
for (var i in options) {
this._settings[i] = options[i];
}
this._createInput();
this._rerouteClicks();
}
// assigning methods to our class
AjaxUpload.prototype = {
setData : function(data){
this._settings.data = data;
},
disable : function(){
this._disabled = true;
},
enable : function(){
this._disabled = false;
},
// removes ajaxupload
destroy : function(){
if(this._input){
if(this._input.parentNode){
this._input.parentNode.removeChild(this._input);
}
this._input = null;
}
},
/**
* Creates invisible file input above the button
*/
_createInput : function(){
var self = this;
var input = d.createElement("input");
input.setAttribute('type', 'file');
input.setAttribute('name', this._settings.name);
var styles = {
'position' : 'absolute'
,'margin': '-5px 0 0 -175px'
,'padding': 0
,'width': '220px'
,'height': '30px'
,'fontSize': '14px'
,'opacity': 0
,'cursor': 'pointer'
,'display' : 'none'
,'zIndex' : 2147483583 //Max zIndex supported by Opera 9.0-9.2x
// Strange, I expected 2147483647
};
for (var i in styles){
input.style[i] = styles[i];
}
// Make sure that element opacity exists
// (IE uses filter instead)
if ( ! (input.style.opacity === "0")){
input.style.filter = "alpha(opacity=0)";
}
this._parentDialog.appendChild(input);
addEvent(input, 'change', function(){
// get filename from input
var file = fileFromPath(this.value);
if(self._settings.onChange.call(self, file, getExt(file)) == false ){
return;
}
// Submit form when value is changed
if (self._settings.autoSubmit){
self.submit();
}
});
// Fixing problem with Safari
// The problem is that if you leave input before the file select dialog opens
// it does not upload the file.
// As dialog opens slowly (it is a sheet dialog which takes some time to open)
// there is some time while you can leave the button.
// So we should not change display to none immediately
addEvent(input, 'click', function(){
self.justClicked = true;
setTimeout(function(){
// we will wait 3 seconds for dialog to open
self.justClicked = false;
}, 3000);
});
this._input = input;
},
_rerouteClicks : function (){
var self = this;
// IE displays 'access denied' error when using this method
// other browsers just ignore click()
// addEvent(this._button, 'click', function(e){
// self._input.click();
// });
var box, dialogOffset = {top:0, left:0}, over = false;
addEvent(self._button, 'mouseover', function(e){
if (!self._input || over) return;
over = true;
box = getBox(self._button);
if (self._parentDialog != d.body){
dialogOffset = getOffset(self._parentDialog);
}
});
// we can't use mouseout on the button,
// because invisible input is over it
addEvent(document, 'mousemove', function(e){
var input = self._input;
if (!input || !over) return;
if (self._disabled){
removeClass(self._button, 'hover');
input.style.display = 'none';
return;
}
var c = getMouseCoords(e);
if ((c.x >= box.left) && (c.x <= box.right) &&
(c.y >= box.top) && (c.y <= box.bottom)){
input.style.top = c.y - dialogOffset.top + 'px';
input.style.left = c.x - dialogOffset.left + 'px';
input.style.display = 'block';
addClass(self._button, 'hover');
} else {
// mouse left the button
over = false;
if (!self.justClicked){
input.style.display = 'none';
}
removeClass(self._button, 'hover');
}
});
},
/**
* Creates iframe with unique name
*/
_createIframe : function(){
// unique name
// We cannot use getTime, because it sometimes return
// same value in safari :(
var id = getUID();
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
iframe.id = id;
iframe.style.display = 'none';
d.body.appendChild(iframe);
return iframe;
},
/**
* Upload file without refreshing the page
*/
submit : function(){
var self = this, settings = this._settings;
if (this._input.value === ''){
// there is no file
return;
}
// get filename from input
var file = fileFromPath(this._input.value);
// execute user event
if (! (settings.onSubmit.call(this, file, getExt(file)) == false)) {
// Create new iframe for this submission
var iframe = this._createIframe();
// Do not submit if user function returns false
var form = this._createForm(iframe);
form.appendChild(this._input);
form.submit();
d.body.removeChild(form);
form = null;
this._input = null;
// create new input
this._createInput();
var toDeleteFlag = false;
addEvent(iframe, 'load', function(e){
if (// For Safari
iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
// For FF, IE
iframe.src == "javascript:'<html></html>';"){
// First time around, do not delete.
if( toDeleteFlag ){
// Fix busy state in FF3
setTimeout( function() {
d.body.removeChild(iframe);
}, 0);
}
return;
}
var doc = iframe.contentDocument ? iframe.contentDocument : frames[iframe.id].document;
// fixing Opera 9.26
if (doc.readyState && doc.readyState != 'complete'){
// Opera fires load event multiple times
// Even when the DOM is not ready yet
// this fix should not affect other browsers
return;
}
// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false"){
// In Opera 9.64 event was fired second time
// when body.innerHTML changed from false
// to server response approx. after 1 sec
return;
}
var response;
if (doc.XMLDocument){
// response is a xml document IE property
response = doc.XMLDocument;
} else if (doc.body){
// response is html document or plain text
response = doc.body.innerHTML;
if (settings.responseType && settings.responseType.toLowerCase() == 'json'){
// If the document was sent as 'application/javascript' or
// 'text/javascript', then the browser wraps the text in a <pre>
// tag and performs html encoding on the contents. In this case,
// we need to pull the original text content from the text node's
// nodeValue property to retrieve the unmangled content.
// Note that IE6 only understands text/html
if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE'){
response = doc.body.firstChild.firstChild.nodeValue;
}
if (response) {
response = window["eval"]("(" + response + ")");
} else {
response = {};
}
}
} else {
// response is a xml document
var response = doc;
}
settings.onComplete.call(self, file, response);
// Reload blank page, so that reloading main page
// does not re-submit the post. Also, remember to
// delete the frame
toDeleteFlag = true;
// Fix IE mixed content issue
iframe.src = "javascript:'<html></html>';";
});
} else {
// clear input to allow user to select same file
// Doesn't work in IE6
// this._input.value = '';
d.body.removeChild(this._input);
this._input = null;
// create new input
this._createInput();
}
},
/**
* Creates form, that will be submitted to iframe
*/
_createForm : function(iframe){
var settings = this._settings;
// method, enctype must be specified here
// because changing this attr on the fly is not allowed in IE 6/7
var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
form.style.display = 'none';
form.action = settings.action;
form.target = iframe.name;
d.body.appendChild(form);
// Create hidden input element for each data key
for (var prop in settings.data){
var el = d.createElement("input");
el.type = 'hidden';
el.name = prop;
el.value = settings.data[prop];
form.appendChild(el);
}
return form;
}
};
})();
jquery code for uploading
$(document).ready(function () {
var btnUpload=$('#browse');
$("#hidauto").css('display','block');
new AjaxUpload(btnUpload, {
action: '<?=site_url('brand/upload_image1/')?>',
name: 'file',
onSubmit: function(file, ext){$("#loadgif1").css("display","block");
if (! (ext && /^(jpg|jpeg|gif|png)$/.test(ext))){
// extension is not allowed
//document.getElementById("loadgif").style.display='block';
$("#loadgif1").css("display","none");
$("#image").css("display","block");
$("#image").html("only jpg,jpeg,png, images are allowed");
return false;
}
},
onComplete: function(file, response){
//alert(response);
if(response=='0'){
$("#primimage1_error").html("This image is too small please upload a bigger one");
$("#loadgif1").css("display","none");
return false;
}
$("#hidauto").css('display','block');
$("#loadgif1").css("display","none");
$("#image").html("");
var r=response;
//document.getElementById("imghid").value=response;
divid=r.replace(new RegExp(".jpg", 'g'),'');
divid=divid.replace(new RegExp(".jpeg", 'g'),'');
divid=divid.replace(new RegExp(".png", 'g'),'');
//alert(divid);
document.getElementById("imghidall").value=document.getElementById("imghidall").value+response+",";
shw='<div style="float: left; height:135px; width:147px;" id='+divid+'><img src="<?php echo base_url();?>uploads/'+response+'" width="125px" height="115px" /><div style="width: 125px;"><input type="radio" name="checkPrimary" title="Set as Primary image" value="'+divid+'" onClick="primaryimg('+"'"+r+"'"+');" style="margin:5px"><img src="<?php echo base_url();?>images/img_delete.png" width="17px" height="17px" title="delete" onClick="delete_image('+"'"+r+"'"+');" width="15px;" height="15px" style="float:right; margin-top:3px;"></div></div>';
// shw='<div style="float: left; height:135px; width:147px;" id='+divid+'><img src="<?php echo base_url();?>uploads/'+response+'" width="125px" height="115px" /><div style="width: 125px;"><input type="checkbox" id="checkPrimary" value="'+divid+'" onClick="primaryimg('+"'"+r+"'"+');" style="margin:5px"><img src="<?php echo base_url();?>images/remove.png" title="delete" onClick="delete_image('+"'"+r+"'"+');" width="15px;" height="15px" style="float:right; margin-top:2px;"></div></div>';
//alert(shw);
$("#hidauto").append( shw );
$("#primimage1_error").html("");
//location.reload();
}
});
});
HTML Code
<div class="r8_prt" style="margin-right: 0px; margin-top: 10px;">
<div class="line1">
<label style="float: left; width: 121px; margin-right:10%;">Upload images : </label><input type="file" name="browse" id="browse" multiple="true" style="float: left;">
<label class="error" for="dwn" id="allimg_error" style="display:block; color: #B94A48;font-size: 11px;font-weight: bold; text-align:center;" ></label>
<label class="error" for="dwn" id="primimage1_error" style="display:block; color: #B94A48;font-size: 11px;font-weight: bold; text-align:center;" ></label>
<label id="loadgif1" style="display:none; width:10px; float:left"><img style="margin-top:-10px" src="<?php echo base_url();?>images/ajax-loader(2).gif"></label>
<div id="image" style="float:left; width:110%; margin-top:20px; color:#F00;">
</div>
<div id="hidauto">
</div>
<input type="hidden" value="" id="imghid" name="imghid">
<input type="hidden" value="" id="imghidall" name="imghidall">
</div>
</div>
Upload function(For Codeigniter)
function upload_image1() {
$ext=$_FILES['file']['name'];
$epld=explode('.',$ext);
$nn= count($epld);$nn-=1;
$photo=date("MdyHis").".".$epld[$nn];
$data = getimagesize($_FILES['file']['tmp_name']);
$width = $data[0];
$height = $data[1]; if($width<250 || $height<250){ echo 0; die(); }
if( move_uploaded_file($_FILES['file']['tmp_name'],"./uploads/".$photo)){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '15360'; //15MB
$config['max_width'] = '0';//'2000'
$config['max_height'] = '0';//'2000'
$config['min_width'] = '250';//'2000'
$config['min_height'] = '250';//'2000'
$this->load->library('upload', $config);
echo $photo;
} }
Delete Image
function delete_image(name)
{
var answer = confirm ("Do you want to delete this image?")
if (!answer)
{
}
else{
var base_url="<?php echo base_url();?>";
$.ajax
({
type: "POST",
url: base_url+"index.php/brand/delete_image/?imgname="+name,
data:'',
success: function(view)
{
name=name+",";
allname=document.getElementById("imghidall").value;
e=document.getElementById("imghidall").value = allname.replace(new RegExp(name, 'g'),'');
divid=name.replace(new RegExp(".jpg,", 'g'),'');
divid=divid.replace(new RegExp(".jpeg,", 'g'),'');
divid=divid.replace(new RegExp(".png,", 'g'),'');
//alert(divid);
document.getElementById(divid).innerHTML="";
$("#"+divid).css('width','0px');
}
});
}
}
Delete image function
function delete_image(){
$file_name=$_GET['imgname'];
unlink(FCPATH . '/uploads/' . $file_name);
unlink(FCPATH . '/uploads/thumb/' . $file_name);
unlink(FCPATH . '/uploads/watermark/' . $file_name);
}
if (isset($_FILES['file']['tmp_name'])) {
for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
$tmpFilePath = $_FILES['file']['tmp_name'][$i];
if ($tmpFilePath != "") {
//. time() . $_FILES['file']['name'][$i] becomes the name of the files
$file[$i] = $newFilePath = "upload/myfolder/" . time() . $_FILES['file']['name'][$i];
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
$file[$i] = $newFilePath = "upload/myfolder/" . time() . $_FILES['file']['name'][$i];
}
}
}
}
PUT THIS SIMPLE SCRIPT INTO PHP SCRIPT OR FUNCTION. NB:
$_FILES['file']
because <input type="file" name="file[]" id="file" />
Related
I'm not a php programmer. Someone ask me help for a web server with problem. I fix everything and update PHP 5.4 to 5.6. Everything work fine on his php program, except file upload.
Message: getimagesize(var/www/myserver/admin/uploads/temp/test.jpg): failed to open stream: No such file or directory
error on this line: $img_info = getimagesize("uploads/temp/$filename");
if($_POST['fileselect'][0] != "")
$filename=$_POST['fileselect'][0];
else
$filename=$_POST['dragfile'];
if(strlen($filename) > 3){
$finalname=time(); //Set a unique filename by the UNIX time
//Convert to jpg if tiff
$img_info = getimagesize("uploads/temp/$filename");
if($img_info['mime'] == "image/tiff"){
$clearname=explode(".", "$filename")[0];
system("convert uploads/temp/\"$filename\"[0] uploads/temp/$clearname.jpg");
unlink("uploads/temp/$filename");
$filename=$clearname.".jpg";
}
The problem probably come from a new code formulation in php5.6, any idea how to fix that ?
UPDATE 2: FILE UPLOAD section...
part of form.php
<form method="post" class="form-horizontal">
<input type="hidden" id="to_upload" name="to_upload" value="/upload.php">
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000000" />
<input type="hidden" id="id_produit" name="id_produit" value="<?php echo $this->mdl_inventory->form_value('idproduit'); ?>" />
<div class="control-group">
<label class="control-label">Nouveau (jpeg): </label>
<div class="controls">
<input type="file" id="fileselect" name="fileselect[]">
</div>
</div>
Does the name fileselect[] can be the problem ? How can i check if the script go in "upload.php" ?
part of upload.php
/* read the source image */
$source_image = imagecreatefromjpeg("$src");
$width = imagesx($source_image);
$height = imagesy($source_image);
$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
if ($fn) {
// AJAX call
file_put_contents(
'uploads/temp/' . $fn,
file_get_contents('php://input')
);
echo "$fn uploaded";
exit();
}else {
// form submit
$files = $_FILES['fileselect'];
foreach ($files['error'] as $id => $err) {
if ($err == UPLOAD_ERR_OK) {
$fn = $files['name'][$id];
move_uploaded_file(
$files['tmp_name'][$id],
'uploads/' . $fn
);
echo "<p>File $fn uploaded.</p>";
}
}
}
ajax script filedrag.js (upload)
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
UploadFile(f);
}
}
// output file information
function ParseFile(file) {
Output(
"<p>File information: <strong>" + file.name +
"</strong> type: <strong>" + file.type +
"</strong> size: <strong>" + file.size +
"</strong> bytes</p>"
);
// display an image
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '" /></p>'
);
}
reader.readAsDataURL(file);
}
// display text
if (file.type.indexOf("text") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong></p><pre>" +
e.target.result.replace(/</g, "<").replace(/>/g, ">") +
"</pre>"
);
}
reader.readAsText(file);
}
}
// upload JPEG files
function UploadFile(file) {
// following line is not necessary: prevents running on SitePoint servers
if (location.host.indexOf("sitepointstatic") >= 0) return
var xhr = new XMLHttpRequest();
if (xhr.upload && (file.type == "image/jpeg" || file.type == "image/tiff" ) && file.size <= $id("MAX_FILE_SIZE").value) {
// create progress bar
var o = $id("progress");
var progress = o.appendChild(document.createElement("p"));
progress.appendChild(document.createTextNode("upload " + file.name));
// progress bar
xhr.upload.addEventListener("progress", function(e) {
var pc = parseInt(100 - (e.loaded / e.total * 100));
progress.style.backgroundPosition = pc + "% 0";
}, false);
// file received/failed
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
progress.className = (xhr.status == 200 ? "success" : "failure");
}
};
// start upload
xhr.open("POST", $id("to_upload").value + "?idproduit=" + $id("id_produit").value, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
$('#dragfile').attr('value', file.name);
}
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton");
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
//submitbutton.style.display = "none";
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
The syntax for the code mentioned is correct for 5.6, no issues with that.
I don't see permissions as the issue as well, otherwise you'd have gotten a 'Permission denied' error.
So, most likely, it looks like, the file that you are looking for does not exist in the folder.
the error was here:
xhr.setRequestHeader("X_FILENAME", file.name);
X-filename... i think it's APACHE UPDATE problem.
Thanks for help.
First of all I'm very new to PHP and a bit better with Jquery. I managed to build an upload iFrame to upload images to a dropbox account for a webshop.
So somebody puts a T-shirt in the cart and then needs to upload some artwork. Customer clicks "upload" and is send to an iFrame which have the dropbox upload script. The url of the iFrame is something like this -> http://webshop.com/dropbox/index.html?id=10102013-88981
So far so good. The problem is however that when two people upload a file with the same name, the first file is being updated. So I need to have an unique id in front of the file. That unique id is the parameter at the end of the url.
So the question is how to get the id at the end of the url and how to place it in front of the uploaded image?
Ideal would be either a prefix for the file name or store everything in it's own folder.
I tried several things but my knowledge is limited, so any help greatly appreciated.
The upload script:
//Start the upload code.
........
......
if(sizeof($_FILES)===0){
echo "<li>No files were uploaded.</li>";
return;
}
foreach ($_FILES['ufiles']['name'] as $key => $value) {
if ($_FILES['ufiles']['error'][$key] !== UPLOAD_ERR_OK) {
echo $_FILES['ufiles']['name'][$key].' DID NOT upload.';
return;
}
$tmpDir = uniqid('/tmp/DropboxUploader-');
if (!mkdir($tmpDir)) {
echo 'Cannot create temporary directory!';
return;
}
$tmpFile = $tmpDir.'/'.str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);
if (!move_uploaded_file($_FILES['ufiles']['tmp_name'][$key], $tmpFile)) {
echo $_FILES['ufiles']['name'][$key].' - Cannot rename uploaded file!';
return;
}
try {
$uploader = new DropboxUploader($drop_account, $drop_pwd );
$uploader->upload($tmpFile, $drop_dir);
echo "<li>".$_FILES['ufiles']['name'][$key]."</li>" ;
// Clean up
if (isset($tmpFile) && file_exists($tmpFile))
unlink($tmpFile);
if (isset($tmpDir) && file_exists($tmpDir))
rmdir($tmpDir);
} catch(Exception $e) {
$error_msg = htmlspecialchars($e->getMessage());
if($error_msg === 'Login unsuccessful.' ) {
echo '<li style="font-weight:bold;color:#ff0000;">Unable to log into Dropbox</li>';
return;
}
if($error_msg === 'DropboxUploader requires the cURL extension.' ) {
echo '<li style="font-weight:bold;color:#ff0000;">Application error - contact admin.</li>';
return;
}
echo '<li>'.htmlspecialchars($e->getMessage()).'</li>';
}
}
UPDATE AS REQUESTED
The form:
<form class="formclass" id="ufileform" method="post" enctype="multipart/form-data">
<fieldset>
<div><span class="fileinput"><input type="file" name="ufiles" id="ufiles" size="32" multiple /></span>
</div>
</fieldset>
<button type="button" id="ubutton">Upload</button>
<button type="button" id="clear5" onclick="ClearUpload();">Delete</button>
<input type="hidden" name="id" id="prefix" value="" />
</form>
Upload.js (file is downloadable as free script on the internet):
(function () {
if (window.FormData) {
var thefiles = document.getElementById('ufiles'), upload = document.getElementById('ubutton');//, password = document.getElementById('pbutton');
formdata = new FormData();
thefiles.addEventListener("change", function (evt) {
var files = evt.target.files; // FileList object
var i = 0, len = this.files.length, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (isValidExt(file.name)) { //if the extension is NOT on the NOT Allowed list, add it and show it.
formdata.append('ufiles[]', file);
output.push('<li>', file.name, ' <span class="exsmall">',
bytesToSize(file.size, 2),
'</span></li>');
document.getElementById('listfiles').innerHTML = '<ul>' + output.join('') + '</ul>';
}
}
document.getElementById('filemsg').innerHTML = '';
document.getElementById('filemsgwrap').style.display = 'none';
document.getElementById('ubutton').style.display = 'inline-block';
document.getElementById('clear5').style.display = 'inline-block';
}, false);
upload.addEventListener('click', function (evt) { //monitors the "upload" button and posts the files when it is clicked
document.getElementById('progress').style.display = 'block'; //shows progress bar
document.getElementById('ufileform').style.display = 'none'; //hide file input form
document.getElementById('filemsg').innerHTML = ''; //resets the file message area
$.ajax({
url: 'upload.php',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function (results) {
document.getElementById('ufileform').style.display = 'block';
document.getElementById('progress').style.display = 'none';
document.getElementById('filemsgwrap').style.display = 'block';
document.getElementById('filemsg').innerHTML = '<ul>' + results + '</ul>';
document.getElementById('listfiles').innerHTML = '<ul><li>Select Files for Upload</ul>';
document.getElementById('ufiles').value = '';
document.getElementById('ubutton').style.display = 'none';
document.getElementById('clear5').style.display = 'none';
formdata = new FormData();
output.length = 0;
}
});
}, false);
} else {
// document.getElementById('passarea').style.display = 'none';
document.getElementById('NoMultiUploads').style.display = 'block';
document.getElementById('NoMultiUploads').innerHTML = '<div>Your browser does not support this application. Try the lastest version of one of these fine browsers</div><ul><li><img src="images/firefox-logo.png" alt="Mozilla Firefox" /></li><li><img src="images/google-chrome-logo.png" alt="Google Chrome Firefox" /></li><li><img src="images/apple-safari-logo.png" alt="Apple Safari" /></li><li><img src="images/maxthon-logo.png" alt="Maxthon" /></li></ul>';
}
document.getElementById('multiload').style.display = 'block';
document.getElementById('ufileform').style.display = 'block';
}());
function ClearUpload() { //clears the list of files in the 'Files to Upload' area and resets everything to be ready for new upload
formdata = new FormData();
output.length = 0;
document.getElementById('ufiles').value = '';
document.getElementById('listfiles').innerHTML = 'Select Files for Upload';
document.getElementById('ubutton').style.display = 'none';
document.getElementById('clear5').style.display = 'none';
document.getElementById('filemsgwrap').style.display = 'none';
}
function getExtension(filename) { //Gets the extension of a file name.
var parts = filename.split('.');
return parts[parts.length - 1];
}
function isValidExt(filename) { //Compare the extension to the list of extensions that are NOT allowed.
var ext = getExtension(filename);
for(var i=0; i<the_ext.length; i++) {
if(the_ext[i] == ext) {
return false;
break;
}
}
return true;
}
Change this line
$tmpFile = $tmpDir.'/'. $_POST['id'] . '-' . str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);
Note the $_POST['id'] which was added
EDIT: Changed to $_POST
Also in your form which you are posting add
<input type="hidden" name="id" value="<?=$_GET['id']; ?>" />
You could simply at time() to your file name.
http://php.net/manual/de/function.time.php
$tmpDir. '/' . time() . str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);
I want to Catch upload file properties array in javascript. Is this possible to do in javascript?
Detail Requirement:
I have html form,which is submitted by javascript function and now i want to add one more field upload file in that form but how can that upload file array can be send via javascript function to my php script
$('#save').click(function(){
var filearray = new Array();
var file = $("#file")[0].files[0];
filearray["filename"] = file.name;
filearray["filesize"] = file.size;
filearray["fileType"] = file.type;
filearray["fileTemp"] = file.tmp_name;
filearray["fileError"] = file.error;
});
i am not getting attribute tmp_name and error in javascript because it generate when file is on server but i am doing this on client side.
File attributes tmp_name and error generated when the file is on server
Try something like this
var extension = new Array(".jpg",".jpeg",".JPEG",".JPG",".PNG",".png",".ico",".ICO",".GIF",".gif");
function CheckExtension(fieldvalue)
{
var thisext = fieldvalue.substr(fieldvalue.lastIndexOf('.'));
for(var i = 0; i < extension.length; i++) {
if(thisext == extension[i]) { return true; }
}
return false;
}
pass the fieldvalue as input file value.
Hope this may help you..
to get file name and extension:
var extension = fileName.split('.').pop();
var name = fileName.split('.')[0];
to get File Size:
$('#youfiletextbox').bind('change', function() {
var fileSize = this.files[0].size);
});
<input type="file" class='img-icon' id="qImage" name="qImage1" accept="image/*" onchange="GetFileInfo('qImage')"/>
function GetFileInfo(imageID) {
var fileInput = document.getElementById(imageID);
var fName;
var fSize;
var fType;
var message = "";
if ('files' in fileInput) {
if (fileInput.files.length == 0) {
alert("Please browse for one or more files.");
} else {
for (var i = 0; i < fileInput.files.length; i++) {
var file = fileInput.files[i];
if ('name' in file) {
fName = file.name;
}
else {
fName = file.fileName;
}
if ('size' in file) {
fSize = file.size;
}
else {
fSize = file.fileSize;
}
if ('type' in file) {
fType = file.type;
}
else {
fType = file.mediaType;
}
}
var extension = fName.split('.').pop();
var size = fSize / 1024;
if(extension == "png" || extension == "jpg" || extension == "svg"){
if(size > 5){
alert("Image size must be less than 5kb.");
document.getElementById(imageID).value = null;
}
} else {
alert("Image type must png, jpg or svg and size must be less than 5kb.");
document.getElementById(imageID).value = null;
}
}
}
else {
if (fileInput.value == "") {
message += "Please browse for one or more files.";
message += "<br />Use the Control or Shift key for multiple selection.";
}
else {
message += "Your browser doesn't support the files property!";
message += "<br />The path of the selected file: " + fileInput.value;
}
document.getElementById ("info").innerHTML = message;
}
}
<div id="info" style="margin-top:20px"></div>
I'm wrestling with an issue involving a log in form which is fetched using Ajax then displayed in a jQuery overlay. The overlay works perfectly, the issue is that when I click submit (using incorrect details) a the overlay closes instead of displaying the appropriate errors. The PHP code is on the login page (admin/index.php).
Button HTML:
<input name="Submit" type="submit" value="Log In" class="submit" />
Form tag HTML:
<form id="loginForm" method="post" action="">
PHP code:
ob_start();
define('INCLUDE_CHECK',true);
include '../includes/config.php';
session_name('cmsLogin');
session_set_cookie_params(2*7*24*60*60);
session_start();
if($_SESSION['id'] && !isset($_COOKIE['cmsRemember']) && !$_SESSION['rememberMe']) {
$_SESSION = array();
session_destroy();
}
if($_SESSION['id'] && isset($_COOKIE['cmsRemember'])) {
header("Location: loggedIn.php");
}
if($_POST['formName']=='login') {
$err = array();
if(!$_POST['email'] || !$_POST['password'])
$err[] = '<strong>Error:</strong> Please ensure the email & password fields have been completed.';
if(!count($err)) {
$_POST['email'] = mysql_real_escape_string($_POST['email']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
$row = mysql_fetch_assoc(mysql_query("SELECT * FROM cms_members WHERE email='{$_POST['email']}' AND password='".md5($_POST['password'])."'"));
if($row['email']) {
$_SESSION['memberID'] = $row['memberID'];
$_SESSION['email'] = $row['email'];
setcookie('cmsRemember',$_POST['rememberMe']);
}
else $err[]='<strong>Error:</strong> The email and/or password you have entered is invalid.';
}
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
header("Location: index.php");
exit;
}
else {
header("Location: loggedIn.php");
}
}
else {
}
$script = '';
Javascript:
(function($){
//closeDOMWindow
$.fn.closeDOMWindow = function(settings){
if(!settings){settings={};}
var run = function(passingThis){
if(settings.anchoredClassName){
var $anchorClassName = $('.'+settings.anchoredClassName);
$anchorClassName.fadeOut('fast',function(){
if($.fn.draggable){
$anchorClassName.draggable('destory').trigger("unload").remove();
}else{
$anchorClassName.trigger("unload").remove();
}
});
if(settings.functionCallOnClose){settings.functionCallAfterClose();}
}else{
var $DOMWindowOverlay = $('#DOMWindowOverlay');
var $DOMWindow = $('#DOMWindow');
$DOMWindowOverlay.fadeOut('fast',function(){
$DOMWindowOverlay.trigger('unload').unbind().remove();
});
$DOMWindow.fadeOut('fast',function(){
if($.fn.draggable){
$DOMWindow.draggable("destroy").trigger("unload").remove();
}else{
$DOMWindow.trigger("unload").remove();
}
});
$(window).unbind('scroll.DOMWindow');
$(window).unbind('resize.DOMWindow');
if($.fn.openDOMWindow.isIE6){$('#DOMWindowIE6FixIframe').remove();}
if(settings.functionCallOnClose){settings.functionCallAfterClose();}
}
};
if(settings.eventType){//if used with $().
return this.each(function(index){
$(this).bind(settings.eventType, function(){
run(this);
return false;
});
});
}else{//else called as $.function
run();
}
};
//allow for public call, pass settings
$.closeDOMWindow = function(s){$.fn.closeDOMWindow(s);};
//openDOMWindow
$.fn.openDOMWindow = function(instanceSettings){
var shortcut = $.fn.openDOMWindow;
//default settings combined with callerSettings////////////////////////////////////////////////////////////////////////
shortcut.defaultsSettings = {
anchoredClassName:'',
anchoredSelector:'',
borderColor:'#FFFFFF',
borderSize:'0',
draggable:0,
eventType:'click', //click, blur, change, dblclick, error, focus, load, mousedown, mouseout, mouseup etc...
fixedWindowY:20,
functionCallOnOpen:null,
functionCallOnClose:null,
height:340,
loader:1,
loaderHeight:32,
loaderImagePath:'images/icon_loader.gif',
loaderWidth:32,
modal:0,
overlay:1,
overlayColor:'#000',
overlayOpacity:'75',
positionLeft:0,
positionTop:10,
positionType:'centered', // centered, anchored, absolute, fixed
width:280,
windowBGColor:'',
windowBGImage:null, // http path
windowHTTPType:'get',
windowPadding:0,
windowSource:'ajax', //inline, ajax, iframe
windowSourceID:'',
windowSourceURL:'',
windowSourceAttrURL:'href'
};
var settings = $.extend({}, $.fn.openDOMWindow.defaultsSettings , instanceSettings || {});
//Public functions
shortcut.viewPortHeight = function(){ return self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;};
shortcut.viewPortWidth = function(){ return self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;};
shortcut.scrollOffsetHeight = function(){ return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;};
shortcut.scrollOffsetWidth = function(){ return self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;};
shortcut.isIE6 = typeof document.body.style.maxHeight === "undefined";
//Private Functions/////////////////////////////////////////////////////////////////////////////////////////////////////////
var sizeOverlay = function(){
var $DOMWindowOverlay = $('#DOMWindowOverlay');
if(shortcut.isIE6){//if IE 6
var overlayViewportHeight = document.documentElement.offsetHeight + document.documentElement.scrollTop - 4;
var overlayViewportWidth = document.documentElement.offsetWidth - 21;
$DOMWindowOverlay.css({'height':overlayViewportHeight +'px','width':overlayViewportWidth+'px'});
}else{//else Firefox, safari, opera, IE 7+
$DOMWindowOverlay.css({'height':'100%','width':'100%','position':'fixed'});
}
};
var sizeIE6Iframe = function(){
var overlayViewportHeight = document.documentElement.offsetHeight + document.documentElement.scrollTop - 4;
var overlayViewportWidth = document.documentElement.offsetWidth - 21;
$('#DOMWindowIE6FixIframe').css({'height':overlayViewportHeight +'px','width':overlayViewportWidth+'px'});
};
var centerDOMWindow = function() {
var $DOMWindow = $('#DOMWindow');
if(settings.height + 50 > shortcut.viewPortHeight()){//added 50 to be safe
$DOMWindow.css('left',Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($DOMWindow.outerWidth())/2));
}else{
$DOMWindow.css('left',Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($DOMWindow.outerWidth())/2));
$DOMWindow.css('top',Math.round(shortcut.viewPortHeight()/2) + shortcut.scrollOffsetHeight() - Math.round(($DOMWindow.outerHeight())/2));
}
};
var centerLoader = function() {
var $DOMWindowLoader = $('#DOMWindowLoader');
if(shortcut.isIE6){//if IE 6
$DOMWindowLoader.css({'left':Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($DOMWindowLoader.innerWidth())/2),'position':'absolute'});
$DOMWindowLoader.css({'top':Math.round(shortcut.viewPortHeight()/2) + shortcut.scrollOffsetHeight() - Math.round(($DOMWindowLoader.innerHeight())/2),'position':'absolute'});
}else{
$DOMWindowLoader.css({'left':'50%','top':'50%','position':'fixed'});
}
};
var fixedDOMWindow = function(){
var $DOMWindow = $('#DOMWindow');
$DOMWindow.css('left', settings.positionLeft + shortcut.scrollOffsetWidth());
$DOMWindow.css('top', + settings.positionTop + shortcut.scrollOffsetHeight());
};
var showDOMWindow = function(instance){
if(arguments[0]){
$('.'+instance+' #DOMWindowLoader').remove();
$('.'+instance+' #DOMWindowContent').fadeIn('fast',function(){if(settings.functionCallOnOpen){settings.functionCallOnOpen();}});
$('.'+instance+ '.closeDOMWindow').click(function(){
$.closeDOMWindow();
return false;
});
}else{
$('#DOMWindowLoader').remove();
$('#DOMWindow').fadeIn('fast',function(){if(settings.functionCallOnOpen){settings.functionCallOnOpen();}});
$('#DOMWindow .closeDOMWindow').click(function(){
$.closeDOMWindow();
return false;
});
}
};
var urlQueryToObject = function(s){
var query = {};
s.replace(/b([^&=]*)=([^&=]*)b/g, function (m, a, d) {
if (typeof query[a] != 'undefined') {
query[a] += ',' + d;
} else {
query[a] = d;
}
});
return query;
};
//Run Routine ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
var run = function(passingThis){
//get values from element clicked, or assume its passed as an option
settings.windowSourceID = $(passingThis).attr('href') || settings.windowSourceID;
settings.windowSourceURL = $(passingThis).attr(settings.windowSourceAttrURL) || settings.windowSourceURL;
settings.windowBGImage = settings.windowBGImage ? 'background-image:url('+settings.windowBGImage+')' : '';
var urlOnly, urlQueryObject;
if(settings.positionType == 'anchored'){//anchored DOM window
var anchoredPositions = $(settings.anchoredSelector).position();
var anchoredPositionX = anchoredPositions.left + settings.positionLeft;
var anchoredPositionY = anchoredPositions.top + settings.positionTop;
$('body').append('<div class="'+settings.anchoredClassName+'" style="'+settings.windowBGImage+';background-repeat:no-repeat;padding:'+settings.windowPadding+'px;overflow:auto;position:absolute;top:'+anchoredPositionY+'px;left:'+anchoredPositionX+'px;height:'+settings.height+'px;width:'+settings.width+'px;background-color:'+settings.windowBGColor+';border:'+settings.borderSize+'px solid '+settings.borderColor+';z-index:10001"><div id="DOMWindowContent" style="display:none"></div></div>');
//loader
if(settings.loader && settings.loaderImagePath !== ''){
$('.'+settings.anchoredClassName).append('<div id="DOMWindowLoader" style="width:'+settings.loaderWidth+'px;height:'+settings.loaderHeight+'px;"><img src="'+settings.loaderImagePath+'" /></div>');
}
if($.fn.draggable){
if(settings.draggable){$('.' + settings.anchoredClassName).draggable({cursor:'move'});}
}
switch(settings.windowSource){
case 'inline'://////////////////////////////// inline //////////////////////////////////////////
$('.' + settings.anchoredClassName+" #DOMWindowContent").append($(settings.windowSourceID).children());
$('.' + settings.anchoredClassName).unload(function(){// move elements back when you're finished
$('.' + settings.windowSourceID).append( $('.' + settings.anchoredClassName+" #DOMWindowContent").children());
});
showDOMWindow(settings.anchoredClassName);
break;
case 'iframe'://////////////////////////////// iframe //////////////////////////////////////////
$('.' + settings.anchoredClassName+" #DOMWindowContent").append('<iframe frameborder="0" hspace="0" wspace="0" src="'+settings.windowSourceURL+'" name="DOMWindowIframe'+Math.round(Math.random()*1000)+'" style="width:100%;height:100%;border:none;background-color:#fff;" class="'+settings.anchoredClassName+'Iframe" ></iframe>');
$('.'+settings.anchoredClassName+'Iframe').load(showDOMWindow(settings.anchoredClassName));
break;
case 'ajax'://////////////////////////////// ajax //////////////////////////////////////////
if(settings.windowHTTPType == 'post'){
if(settings.windowSourceURL.indexOf("?") !== -1){//has a query string
urlOnly = settings.windowSourceURL.substr(0, settings.windowSourceURL.indexOf("?"));
urlQueryObject = urlQueryToObject(settings.windowSourceURL);
}else{
urlOnly = settings.windowSourceURL;
urlQueryObject = {};
}
$('.' + settings.anchoredClassName+" #DOMWindowContent").load(urlOnly,urlQueryObject,function(){
showDOMWindow(settings.anchoredClassName);
});
}else{
if(settings.windowSourceURL.indexOf("?") == -1){ //no query string, so add one
settings.windowSourceURL += '?';
}
$('.' + settings.anchoredClassName+" #DOMWindowContent").load(
settings.windowSourceURL + '&random=' + (new Date().getTime()),function(){
showDOMWindow(settings.anchoredClassName);
});
}
break;
}
}else{//centered, fixed, absolute DOM window
//overlay & modal
if(settings.overlay){
$('body').append('<div id="DOMWindowOverlay" style="z-index:10000;display:none;position:absolute;top:0;left:0;background-color:'+settings.overlayColor+';filter:alpha(opacity='+settings.overlayOpacity+');-moz-opacity: 0.'+settings.overlayOpacity+';opacity: 0.'+settings.overlayOpacity+';"></div>');
if(shortcut.isIE6){//if IE 6
$('body').append('<iframe id="DOMWindowIE6FixIframe" src="blank.html" style="width:100%;height:100%;z-index:9999;position:absolute;top:0;left:0;filter:alpha(opacity=0);"></iframe>');
sizeIE6Iframe();
}
sizeOverlay();
var $DOMWindowOverlay = $('#DOMWindowOverlay');
$DOMWindowOverlay.fadeIn('fast');
if(!settings.modal){$DOMWindowOverlay.click(function(){$.closeDOMWindow();});}
}
//loader
if(settings.loader && settings.loaderImagePath !== ''){
$('body').append('<div id="DOMWindowLoader" style="z-index:10002;width:'+settings.loaderWidth+'px;height:'+settings.loaderHeight+'px;"><img src="'+settings.loaderImagePath+'" /></div>');
centerLoader();
}
//add DOMwindow
$('body').append('<div id="DOMWindow" style="background-repeat:no-repeat;'+settings.windowBGImage+';overflow:auto;padding:'+settings.windowPadding+'px;display:none;height:'+settings.height+'px;width:'+settings.width+'px;background-color:'+settings.windowBGColor+';border:'+settings.borderSize+'px solid '+settings.borderColor+'; position:absolute;z-index:10001"></div>');
var $DOMWindow = $('#DOMWindow');
//centered, absolute, or fixed
switch(settings.positionType){
case 'centered':
centerDOMWindow();
if(settings.height + 50 > shortcut.viewPortHeight()){//added 50 to be safe
$DOMWindow.css('top', (settings.fixedWindowY + shortcut.scrollOffsetHeight()) + 'px');
}
break;
case 'absolute':
$DOMWindow.css({'top':(settings.positionTop+shortcut.scrollOffsetHeight())+'px','left':(settings.positionLeft+shortcut.scrollOffsetWidth())+'px'});
if($.fn.draggable){
if(settings.draggable){$DOMWindow.draggable({cursor:'move'});}
}
break;
case 'fixed':
fixedDOMWindow();
break;
case 'anchoredSingleWindow':
var anchoredPositions = $(settings.anchoredSelector).position();
var anchoredPositionX = anchoredPositions.left + settings.positionLeft;
var anchoredPositionY = anchoredPositions.top + settings.positionTop;
$DOMWindow.css({'top':anchoredPositionY + 'px','left':anchoredPositionX+'px'});
break;
}
$(window).bind('scroll.DOMWindow',function(){
if(settings.overlay){sizeOverlay();}
if(shortcut.isIE6){sizeIE6Iframe();}
if(settings.positionType == 'centered'){centerDOMWindow();}
if(settings.positionType == 'fixed'){fixedDOMWindow();}
});
$(window).bind('resize.DOMWindow',function(){
if(shortcut.isIE6){sizeIE6Iframe();}
if(settings.overlay){sizeOverlay();}
if(settings.positionType == 'centered'){centerDOMWindow();}
});
switch(settings.windowSource){
case 'inline'://////////////////////////////// inline //////////////////////////////////////////
$DOMWindow.append($(settings.windowSourceID).children());
$DOMWindow.unload(function(){// move elements back when you're finished
$(settings.windowSourceID).append($DOMWindow.children());
});
showDOMWindow();
break;
case 'iframe'://////////////////////////////// iframe //////////////////////////////////////////
$DOMWindow.append('<iframe frameborder="0" hspace="0" wspace="0" src="'+settings.windowSourceURL+'" name="DOMWindowIframe'+Math.round(Math.random()*1000)+'" style="width:100%;height:100%;border:none;background-color:#fff;" id="DOMWindowIframe" ></iframe>');
$('#DOMWindowIframe').load(showDOMWindow());
break;
case 'ajax'://////////////////////////////// ajax //////////////////////////////////////////
if(settings.windowHTTPType == 'post'){
if(settings.windowSourceURL.indexOf("?") !== -1){//has a query string
urlOnly = settings.windowSourceURL.substr(0, settings.windowSourceURL.indexOf("?"));
urlQueryObject = urlQueryToObject(settings.windowSourceURL);
}else{
urlOnly = settings.windowSourceURL;
urlQueryObject = {};
}
$DOMWindow.load(urlOnly,urlQueryObject,function(){
showDOMWindow();
});
}else{
if(settings.windowSourceURL.indexOf("?") == -1){ //no query string, so add one
settings.windowSourceURL += '?';
}
$DOMWindow.load(
settings.windowSourceURL + '&random=' + (new Date().getTime()),function(){
showDOMWindow();
});
}
break;
}
}//end if anchored, or absolute, fixed, centered
};//end run()
if(settings.eventType){//if used with $().
return this.each(function(index){
$(this).bind(settings.eventType,function(){
run(this);
return false;
});
});
}else{//else called as $.function
run();
}
};//end function openDOMWindow
//allow for public call, pass settings
$.openDOMWindow = function(s){$.fn.openDOMWindow(s);};
})(jQuery);
Any help/ideas would be greatly appresiated.
Thanks,
#rrfive
Hi Reason that your modal closes is that when you click submit your running your backend code, this being PHP and with your PHP you are redirecting the user if the result is negative, you need to capture the response from your PHP rather than having your PHP do a redirect.
What you can do is make your submit an ajax submit and set the data response to json, then you can write a json response that your jquery can understand, this way all the validation will be done on the backend in the background without needed to redirect.
i have two page, the first page is index.php i also using facebox framework in it. the second page is addevent.php i've tried in many ways to catch the value of single checkbox in addevent.php and passing it to index.php. but it didn't show the value. so is there someting wrong with my code ? what i'm miss ? any help would be appreciate..
index.php
echo ">".$check=$_REQUEST['check'];
echo "check[0]: ".$check[0];
<head>
<script src="inc/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="inc/facebox.js" type="text/javascript"></script>
<body>
<a href="addevent.php" rel="facebox" >link</a>
</body>
addevent.php
<head>
<script src="inc/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="inc/facebox.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
function AddEventAgenda(){
//--- i've tried this method & firebug said:document.eventAgendaForm.checkName[0] is undefined----
var elemLength = document.eventAgendaForm.checkName.length;
if (elemLength==undefined) {
elemLength=1;
if (document.eventAgendaForm.checkName.checked) {
// we know the one and only is checked
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
} else {
for (var i = 0; i<elemLength; i++) {
if (eventAgendaForm.checkName[i].checked) {
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//--- also this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var len = document.eventAgendaForm.checkName.length;
if(len == undefined) len = 1;
for (i = 0; i < len; i++){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var formNodes = document.eventAgendaForm.getElementsByTagName('input');
for (var i=0;i<formNodes.length;i++) {
/* do something with the name/value/id or checked-state of formNodes[i] */
if(document.eventAgendaForm.checkName[i].checked){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
if (typeof document.eventAgendaForm.checkName.length === 'undefined') {
/*then there is just one checkbox with the name 'user' no array*/
if (document.eventAgendaForm.checkName.checked == true )
{
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
}else{
/*then there is several checkboxs with the name 'user' making an array*/
for(var i = 0, max = document.eventAgendaForm.checkName.length; i < max; i++){
if (document.eventAgendaForm.checkName[i].checked == true )
{
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//-----------------------------------------------
window.location="index.php?tes=1" + check; // display the result
$(document).trigger('close.facebox');
}
</script>
<script type="text/javascript">
// i don't know if these code have connection with checkbox or not?
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != "function") {
window.onload = func;
} else {
window.onload = function () {
oldonload();
func();
}
}
}
addLoadEvent(function () {
initChecklist();
});
function initChecklist() {
if (document.all && document.getElementById) {
// Get all unordered lists
var lists = document.getElementsByTagName("ul");
for (i = 0; i < lists.length; i++) {
var theList = lists[i];
// Only work with those having the class "checklist"
if (theList.className.indexOf("checklist") > -1) {
var labels = theList.getElementsByTagName("label");
// Assign event handlers to labels within
for (var j = 0; j < labels.length; j++) {
var theLabel = labels[j];
theLabel.onmouseover = function() { this.className += " hover"; };
theLabel.onmouseout = function() { this.className = this.className.replace(" hover", ""); };
}
}
}
}
}
</script>
</head>
<form name="eventAgendaForm" id="eventAgendaForm" >
<ul class="checklist cl3">
<li ><label for="c1">
<input id="checkId" name="checkName" value="1" type="checkbox" >
</label></li></ul>
<input class="tombol" type="button" name="Add" value="Add" onclick="AddEventAgenda()" />
</form>
why not use jQuery if you are including jQuery library?
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").val();//gets you the value regardless if checked or not
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").attr("checked"); //returns checked status
or
var global_variable=""; //should be initialized outside any function
jQuery("#FORM_ID_HERE").children(":input[type='checkbox']").each(function(){
if (jQuery(this).attr("checked"))global_variable+="&"+jQuery(this).attr("name")+"="+jQuery(this).val();
});
this is just a suggestion to start from, not ideal. the ideal part is to use [] in your form.