Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I am new to Jquery and ajax.
I need to upload multiple images to server folder and store the details in a db table. After uploading, I need to display all images which set as 'active' in database.( I have looked into many codes which are not working for me)
After that I need to drag some images to an area and also need to store dragged images information in an another table.
Anyone have any idea?Please help me?
Thanks
Nowadays Dropzone.js is the best js plugin to upload multiple images using drag and drop.
official site. https://www.dropzonejs.com/
A complete example of the demo is here.
https://learncodeweb.com/web-development/drag-drop-images-with-bootstrap-4-and-reorder-using-php-jquery-and-ajax/
For uploading multiple images you can use this script. By using single browse button you can upload multiple images
$(function(){
var btnUpload=$('#photo_0'); // id of browse button
new AjaxUpload(btnUpload, {
action: 'url_to_upload_function',
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif|JPG|PNG|GIF|JPEG)$/.test(ext))){
$("#photo_div1").html('Only JPG,PNG,GIF files are allowed'); //
return false;
}
var path="<?=base_url()?>images/wait.gif"; //losding image
$("#photo_div1").html("<img src="+path+" width='32' height='32' style='border:#b6b6b6 solid 1px;'>");
},
onComplete: function(file, response){
response = jQuery.trim(response);
if(response=="error")
{
$("#photo_error").css("display","block");
$("#upload_photo1").html("");
}
else if(response!="error")
{
$("#photo_error").css("display","none");
$("#photo_div1").html("");
var path="uploads/"+response; //echo the image name from the upload function
var img="<table><tr><td ><img src="+path+" style='border:#b6b6b6 solid 1px;'></td></tr></table>";
$("#img_div1").html(img);// display the image in a div it will display only one image. If you want to add more you can code according to that by using append or something like that
$("#upload_photo1").val(response);
$("#photo_hid1").val(response);
} else
{
alert("error");
}
}
});
});
YOU HAVE TO INCLUDE THIS FILE ALSO ajaxupload.js
/**
* Ajax upload
* Project page - http://valums.com/ajax-upload/
* Copyright (c) 2008 Andris Valums, http://valums.com
* Licensed under the MIT license (http://valums.com/mit-license/)
* Version 3.5 (23.06.2009)
*/
/**
* Changes from the previous version:
* 1. Added better JSON handling that allows to use 'application/javascript' as a response
* 2. Added demo for usage with jQuery UI dialog
* 3. Fixed IE "mixed content" issue when used with secure connections
*
* For the full changelog please visit:
* http://valums.com/ajax-upload-changelog/
*/
(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,' ');
}
// getOffset function copied from jQuery lib (http://jquery.com/)
if (document.documentElement["getBoundingClientRect"]){
// Get Offset using getBoundingClientRect
// http://ejohn.org/blog/getboundingclientrect-is-awesome/
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){
// pageX/Y is not supported in IE
// http://www.quirksmode.org/dom/w3c_cssom.html
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();
// Remove ie6 "This page contains both secure and nonsecure items" prompt
// http://tinyurl.com/77w9wh
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;
}
};
})();
and for drag and drop you need to write another function for that you can refer this site or this
http://www.plupload.com/example_queuewidget.php
Here you can find a nice plugin that will help you to upload multiple images.I have used this and works well for me.
Related
I'm setting up web-based application using cakePHP, on one point i need to scan barcode then input the barcode result to text-input then run the calculation.
I want to open this web-based app on android tablet on its browser, then my idea is to provide button, on press it will open barcode scanner, then on scanning, it will insert the scanning result to the web-based app in the browser of the android tablet i have.
I tried to explore and find how to do it, but find none.
Is there any idea or insight if this possible? so I can only use 1 tablet device to run web-based system and run barcode scanner on that same tablet.
That is not quite possible in this case with PHP.
PHP is the script that runs on the server, doing things and/or dumping out data (HTML, files, JS, etc.) to the client's browser.
From what I understand, you want to run the barcode scanner on the client side, where it's not PHP that's running, but most likely Javascript.
You can do with JS inside HTML page.
For barcode scanning you need a barcodescanner.js file :
(function ($) {
$.fn.scannerDetection = function (options) {
// If string given, call onComplete callback
if (typeof options === "string") {
this.each(function () {
this.scannerDetectionTest(options);
});
return this;
}
// If false (boolean) given, deinitialize plugin
if (options === false) {
this.each(function () {
this.scannerDetectionOff();
});
return this;
}
var defaults = {
onComplete: false, // Callback after detection of a successfull scanning (scanned string in parameter)
onError: false, // Callback after detection of a unsuccessfull scanning (scanned string in parameter)
onReceive: false, // Callback after receiving and processing a char (scanned char in parameter)
onKeyDetect: false, // Callback after detecting a keyDown (key char in parameter) - in contrast to onReceive, this fires for non-character keys like tab, arrows, etc. too!
timeBeforeScanTest: 100, // Wait duration (ms) after keypress event to check if scanning is finished
avgTimeByChar: 30, // Average time (ms) between 2 chars. Used to do difference between keyboard typing and scanning
minLength: 6, // Minimum length for a scanning
endChar: [9, 13], // Chars to remove and means end of scanning
startChar: [], // Chars to remove and means start of scanning
ignoreIfFocusOn: false, // do not handle scans if the currently focused element matches this selector
scanButtonKeyCode: false, // Key code of the scanner hardware button (if the scanner button a acts as a key itself)
scanButtonLongPressThreshold: 3, // How many times the hardware button should issue a pressed event before a barcode is read to detect a longpress
onScanButtonLongPressed: false, // Callback after detection of a successfull scan while the scan button was pressed and held down
stopPropagation: false, // Stop immediate propagation on keypress event
preventDefault: false // Prevent default action on keypress event
};
if (typeof options === "function") {
options = { onComplete: options }
}
if (typeof options !== "object") {
options = $.extend({}, defaults);
} else {
options = $.extend({}, defaults, options);
}
this.each(function () {
var self = this, $self = $(self), firstCharTime = 0, lastCharTime = 0, stringWriting = '', callIsScanner = false, testTimer = false, scanButtonCounter = 0;
var initScannerDetection = function () {
firstCharTime = 0;
stringWriting = '';
scanButtonCounter = 0;
};
self.scannerDetectionOff = function () {
$self.unbind('keydown.scannerDetection');
$self.unbind('keypress.scannerDetection');
}
self.isFocusOnIgnoredElement = function () {
if (!options.ignoreIfFocusOn) return false;
if (typeof options.ignoreIfFocusOn === 'string') return $(':focus').is(options.ignoreIfFocusOn);
if (typeof options.ignoreIfFocusOn === 'object' && options.ignoreIfFocusOn.length) {
var focused = $(':focus');
for (var i = 0; i < options.ignoreIfFocusOn.length; i++) {
if (focused.is(options.ignoreIfFocusOn[i])) {
return true;
}
}
}
return false;
}
self.scannerDetectionTest = function (s) {
// If string is given, test it
if (s) {
firstCharTime = lastCharTime = 0;
stringWriting = s;
}
if (!scanButtonCounter) {
scanButtonCounter = 1;
}
// If all condition are good (length, time...), call the callback and re-initialize the plugin for next scanning
// Else, just re-initialize
if (stringWriting.length >= options.minLength && lastCharTime - firstCharTime < stringWriting.length * options.avgTimeByChar) {
if (options.onScanButtonLongPressed && scanButtonCounter > options.scanButtonLongPressThreshold) options.onScanButtonLongPressed.call(self, stringWriting, scanButtonCounter);
else if (options.onComplete) options.onComplete.call(self, stringWriting, scanButtonCounter);
$self.trigger('scannerDetectionComplete', { string: stringWriting });
initScannerDetection();
return true;
} else {
if (options.onError) options.onError.call(self, stringWriting);
$self.trigger('scannerDetectionError', { string: stringWriting });
initScannerDetection();
return false;
}
}
$self.data('scannerDetection', { options: options }).unbind('.scannerDetection').bind('keydown.scannerDetection', function (e) {
// If it's just the button of the scanner, ignore it and wait for the real input
if (options.scanButtonKeyCode !== false && e.which == options.scanButtonKeyCode) {
scanButtonCounter++;
// Cancel default
e.preventDefault();
e.stopImmediatePropagation();
}
// Add event on keydown because keypress is not triggered for non character keys (tab, up, down...)
// So need that to check endChar and startChar (that is often tab or enter) and call keypress if necessary
else if ((firstCharTime && options.endChar.indexOf(e.which) !== -1)
|| (!firstCharTime && options.startChar.indexOf(e.which) !== -1)) {
// Clone event, set type and trigger it
var e2 = jQuery.Event('keypress', e);
e2.type = 'keypress.scannerDetection';
$self.triggerHandler(e2);
// Cancel default
e.preventDefault();
e.stopImmediatePropagation();
}
// Fire keyDetect event in any case!
if (options.onKeyDetect) options.onKeyDetect.call(self, e);
$self.trigger('scannerDetectionKeyDetect', { evt: e });
}).bind('keypress.scannerDetection', function (e) {
if (this.isFocusOnIgnoredElement()) return;
if (options.stopPropagation) e.stopImmediatePropagation();
if (options.preventDefault) e.preventDefault();
if (firstCharTime && options.endChar.indexOf(e.which) !== -1) {
e.preventDefault();
e.stopImmediatePropagation();
callIsScanner = true;
} else if (!firstCharTime && options.startChar.indexOf(e.which) !== -1) {
e.preventDefault();
e.stopImmediatePropagation();
callIsScanner = false;
} else {
if (typeof (e.which) != 'undefined') {
stringWriting += String.fromCharCode(e.which);
}
callIsScanner = false;
}
if (!firstCharTime) {
firstCharTime = Date.now();
}
lastCharTime = Date.now();
if (testTimer) clearTimeout(testTimer);
if (callIsScanner) {
self.scannerDetectionTest();
testTimer = false;
} else {
testTimer = setTimeout(self.scannerDetectionTest, options.timeBeforeScanTest);
}
if (options.onReceive) options.onReceive.call(self, e);
$self.trigger('scannerDetectionReceive', { evt: e });
});
});
return this;
}
})(jQuery);
For usecase inside a HTML :
<script type="text/javascript">
$(document).scannerDetection({
timeBeforeScanTest: 200, // wait for the next character for upto 200ms
startChar: [120], // Prefix character for the cabled scanner (OPL6845R)
endChar: [13], // be sure the scan is complete if key 13 (enter) is detected
avgTimeByChar: 40, // it's not a barcode if a character takes longer than 40ms
onComplete: function(barcode, qty) {
console.log(barcode);
console.log(qty);
// barcode number code
// qty scanned by barcode scanner
},
onKeyDetect: function(event) {
return false;
}
});
</script>
Below is the code which I use to upload images through dropzone.
<script>
Dropzone.options.uploaddeadlineimages = {
// The camelized version of the ID of the form element
// The configuration
paramName: 'files',
url:"<?=base_url()."Product/upload_listing_images";?>",
dictDefaultMessage: "<img src='<?=base_url()."public/images/";?>/frontend/camera-black.png'><h2>Drag and drop your photos here to upload</h2><p><a href='javascript:void(0)'>Or Click here to browse for photos</a></p>",
uploadMultiple: false,
createImageThumbnails: true,
addRemoveLinks: true,
parallelUploads:100,
dictInvalidFileType:'Please upload only valid file type(png,jpg,gif,pdf)',
clickable:true,
maxFiles:100,
autoProcessQueue: true,
success: function( file, response ) {
var return_value = response;
var old_value = $('#listing_images').val();
if(old_value=="" || old_value==" " || old_value==null){
var new_value = return_value;
}else{
var new_value = old_value+","+return_value;
}
$('#listing_images').val(new_value);
},
// The setting up of the dropzone
init: function() {
var myDropzone = this;
//alert after success
this.on('queuecomplete', function( file, resp ){
//alert('hahahahahaha');
});
// First change the button to actually tell Dropzone to process the queue.
document.getElementById("create_listing_button").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
}
</script>
the code has this parth which is used to append the new filename into hidden field so that i can save those names in database then. but the problem is that when i click on delete button i need to delete the name of that file from the hidden field too. I am getting an encrypted name from the server.
success: function( file, response ) {
var return_value = response;
var old_value = $('#listing_images').val();
if(old_value=="" || old_value==" " || old_value==null){
var new_value = return_value;
}else{
var new_value = old_value+","+return_value;
}
$('#listing_images').val(new_value);
},
I don't need the exact code. I just need a method by which i can pass the new filename to a function when i click on delete button. this should not prevent the delete from doing it default function
well i found an answer . just update the success part according to your need. but as in my case i needed the image name as id of preview element. it will be done in this way.
success: function( file, response ) {
var return_value = response;
var old_value = $('#listing_images').val();
if(old_value=="" || old_value==" " || old_value==null){
var new_value = return_value;
file.previewElement.id = response;
}else{
file.previewElement.id = response;
var new_value = old_value+","+return_value;
}
$('#listing_images').val(new_value);
},
to change the value of list after delete button just add the following code in dropzone.js file(just the way i did it).
the code starts from line number 274. just change it from this
removeFileEvent = (function(_this) {
return function(e) {
e.preventDefault();
e.stopPropagation();
if (file.status === Dropzone.UPLOADING) {
return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() {
return _this.removeFile(file);
});
} else {
if (_this.options.dictRemoveFileConfirmation) {
return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() {
return _this.removeFile(file);
});
} else {
return _this.removeFile(file);
}
}
};
})(this);
_ref2 = file.previewElement.querySelectorAll("[data-dz-remove]");
_results = [];
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
removeLink = _ref2[_k];
_results.push(removeLink.addEventListener("click", removeFileEvent));
}
return _results;
}
},
to this(just four lines added. do it carefully, otherwise you can mess up all)
removeFileEvent = (function(_this) {
return function(e) {
e.preventDefault();
e.stopPropagation();
if (file.status === Dropzone.UPLOADING) {
return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() {
return _this.removeFile(file);
});
} else {
if (_this.options.dictRemoveFileConfirmation) {
return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() {
var id = $(this).closest("div").prop("id");
update_img_list(id);
return _this.removeFile(file);
});
} else {
var id = $(this).closest("div").prop("id");
update_img_list(id);
return _this.removeFile(file);
}
}
};
})(this);
_ref2 = file.previewElement.querySelectorAll("[data-dz-remove]");
_results = [];
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
removeLink = _ref2[_k];
_results.push(removeLink.addEventListener("click", removeFileEvent));
}
return _results;
}
},
add this function at the end of file change ('#listing_images') to ('#id_of_your_field_which_contains_the_list')
function update_img_list(id){
var list = $('#listing_images').val();
separator = ",";
var values = list.split(separator);
for(var i = 0 ; i < values.length ; i++) {
if(values[i] == id) {
values.splice(i, 1);
$('#listing_images').val(values.join(separator)) ;
}
}
return list;
}
I created function to send email with a back link to my site, I'm using codeigniter framework
after user click that particular link (back link) on email, user redirects to my page which has an iframe.
i used that iframe to submit a form with file input, with out page refreshing.
When user coming through that link using gmail in IE9 browser the form.submit() function fails, in other browsers it works properly and other email(except gmail) too.
pleas help me to find solution
thank you.
update
actually I'm using the ajaxupload jquery library, it fails on the line form.submit(); at above scenario
/* Creates form, that will be submitted to iframe
* #param {Element} iframe Where to submit
* #return {Element} form
*/
_createForm: function(iframe){
var settings = this._settings;
// We can't use the following code in IE6
// var form = document.createElement('form');
// form.setAttribute('method', 'post');
// form.setAttribute('enctype', 'multipart/form-data');
// Because in this case file won't be attached to request
var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
form.setAttribute('action', settings.action);
form.setAttribute('target', iframe.name);
form.style.display = 'none';
document.body.appendChild(form);
// Create hidden input element for each data key
for (var prop in settings.data) {
if (settings.data.hasOwnProperty(prop)){
var el = document.createElement("input");
el.setAttribute('type', 'hidden');
el.setAttribute('name', prop);
el.setAttribute('value', settings.data[prop]);
form.appendChild(el);
}
}
return form;
},
/**
* Gets response from iframe and fires onComplete event when ready
* #param iframe
* #param file Filename to use in onComplete callback
*/
_getResponse : function(iframe, file){
// getting response
var toDeleteFlag = false, self = this, settings = this._settings;
addEvent(iframe, 'load', function(){
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.
// We reload to blank page, so that reloading main page
// does not re-submit the post.
if (toDeleteFlag) {
// Fix busy state in FF3
setTimeout(function(){
removeNode(iframe);
}, 0);
}
return;
}
var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document;
// fixing Opera 9.26,10.00
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 Internet Explorer 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') {
doc.normalize();
response = doc.body.firstChild.firstChild.nodeValue;
}
if (response) {
response = eval("(" + response + ")");
} else {
response = {};
}
}
} else {
// response is a xml document
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>';";
});
},
/**
* Upload file contained in this._input
*/
submit: function(){
var self = this, settings = this._settings;
if ( ! this._input || this._input.value === ''){
return;
}
var file = fileFromPath(this._input.value);
// user returned false to cancel upload
if (false === settings.onSubmit.call(this, file, getExt(file))){
this._clearInput();
return;
}
// sending request
var iframe = this._createIframe();
var form = this._createForm(iframe);
// assuming following structure
// div -> input type='file'
removeNode(this._input.parentNode);
removeClass(self._button, self._settings.hoverClass);
removeClass(self._button, self._settings.focusClass);
form.appendChild(this._input);
form.submit();
// request set, clean up
removeNode(form); form = null;
removeNode(this._input); this._input = null;
// Get response from iframe and fire onComplete event when ready
this._getResponse(iframe, file);
// get ready for next request
this._createInput();
}
};
Check the the code is in iframe if not specify the iframe in form.submit(), i.e.
document.iframename.form.submit();
I'm receiving the following error on this line of code
select.up().appendChild(sw);
With error "SCRIPT438: Object doesn't support property or method 'up' "
This only happens in Internet Explorer... Chrome, Safari, and Firefox all run the code fine. I'm unable to find anything via Google searching for "select.up()". This code isn't my own and I'm not very adept with using DOM in Javascript.
Here is rest of the code:
<?php
$swatches = $this->get_option_swatches();
?>
<script type="text/javascript">
document.observe('dom:loaded', function() {
try {
var swatches = <?php echo Mage::helper('core')->jsonEncode($swatches); ?>;
function find_swatch(key, value) {
for (var i in swatches) {
if (swatches[i].key == key && swatches[i].value == value)
return swatches[i];
}
return null;
}
function has_swatch_key(key) {
for (var i in swatches) {
if (swatches[i].key == key)
return true;
}
return false;
}
function create_swatches(label, select) {
// create swatches div, and append below the <select>
var sw = new Element('div', {'class': 'swatches-container'});
select.up().appendChild(sw);
// store these element to use later for recreate swatches
select.swatchLabel = label;
select.swatchElement = sw;
// hide select
select.setStyle({position: 'absolute', top: '-9999px'})
$A(select.options).each(function(opt, i) {
if (opt.getAttribute('value')) {
var elm;
var key = trim(opt.innerHTML);
// remove price
if (opt.getAttribute('price')) key = trim(key.replace(/\+([^+]+)$/, ''));
var item = find_swatch(label, key);
if (item)
elm = new Element('img', {
src: '<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?>swatches/'+item.img,
alt: opt.innerHTML,
title: opt.innerHTML,
'class': 'swatch-img'});
else {
console.debug(label, key, swatches);
elm = new Element('a', {'class': 'swatch-span'});
elm.update(opt.innerHTML);
}
elm.observe('click', function(event) {
select.selectedIndex = i;
fireEvent(select, 'change');
var cur = sw.down('.current');
if (cur) cur.removeClassName('current');
elm.addClassName('current');
});
sw.appendChild(elm);
}
});
}
function recreate_swatches_recursive(select) {
// remove the old swatches
if (select.swatchElement) {
select.up().removeChild(select.swatchElement);
select.swatchElement = null;
}
// create again
if (!select.disabled)
create_swatches(select.swatchLabel, select);
// recursively recreate swatches for the next select
if (select.nextSetting)
recreate_swatches_recursive(select.nextSetting);
}
function fireEvent(element,event){
if (document.createEventObject){
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
else{
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}
function trim(str) {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
$$('#product-options-wrapper dt').each(function(dt) {
// get custom option's label
var label = '';
$A(dt.down('label').childNodes).each(function(node) {
if (node.nodeType == 3) label += node.nodeValue;
});
label = trim(label);
var dd = dt.next();
var select = dd.down('select');
if (select && has_swatch_key(label)) {
create_swatches(label, select);
// if configurable products, recreate swatches of the next select when the current select change
if (select.hasClassName('super-attribute-select')) {
select.observe('change', function() {
recreate_swatches_recursive(select.nextSetting);
});
}
}
});
}
catch(e) {
alert("Color Swatches javascript error. Please report this error to support#ikova.com. Error:" + e.message);
}
});
</script>
Appreciate any insight anyone could give me!
I'm pretty sure up() is a PrototypeJS method, so i'm pretty sure you would need it to work.
http://prototypejs.org/api/element/up
I m also facing this problem. so, i comment
var sw = new Element('div', {'class': 'swatches-container'});
$(select).up().appendChild(sw);
select.setStyle({position: 'absolute', top: '-9999px'})
lines from function create_swatches
and paste it in function trim(str).
After this i did not error again.
I am using jquery + the hashchange plugin from ben alman. Below is a standard way to grab the hash name and load in content
$(window).hashchange(function() {
var hash = location.hash;
var array_url = hash.split('#');
var page = $(array_url).last()[0];
$('#content').load( page + '.php', function(){
});
});
But is there any way to do this by grabbing some other variable assigned on a click function or sorted through php, perhaps?
I am working with a multi-artist portfolio site that hands out unique three-four letter codes to images
I'd like to serve these images up through unique urls. This has to be through ajax for many reasons.
I had difficulty adding other ajax history options because this page is already using ajax pagination (to load this content) and lots of htaccess url modrewrites.
I am thinking this might just be impossible.
Here is my current code
$('a.photo').click(function () {
var url = $(this).attr('href'),
image = new Image();
image.src = url;
var clickedLink = $(this).attr('id');
location.hash = clickedLink;
image.onload = function () {
$('#content').empty().append(image);
};
image.onerror = function () {
$('#content').empty().html('That image is not available.');
}
$('#content').empty().html('Loading...');
return false;
});
$(window).hashchange( function(){
var hash = location.hash;
var url = ( hash.replace( /^#/, '' ) || 'blank' );
document.title = url;
})
$(window).hashchange();
and my html / php :
$thethumb = customuniqueidfunc();
<a href="[IMG URL]"
class="photo gotdesc nohover" rel="<?php echo $row['description'] ?>"
id="<?php echo $thethumb; ?>">
This works insofar as the image from the href attr loads into the #content div and the hash from the id attr is added as a hash to the url and to the title of the page, but I am lacking any mechanism to combine the click and the hashchange function, so that each hash actually corresponds to the image.
One method I've used for this before is to run a hash polling function. You can see it in action at this page:
http://www.webskethio.com/#services
Here is the javascript for that page:
http://www.webskethio.com/ws.js
Relevant code:
function pollHash() {
//exit function if hash hasn't changed since last check
if (window.location.hash==recentHash) {
return;
}
//hash has changed, update recentHash for future checks
recentHash = window.location.hash;
//run AJAX to update page using page identfier from hash
initializeFromUrl(recentHash.substr(1));
}
$(document).ready(function(){
/* code removed for readability */
setInterval('pollHash()',100); // Important piece
/* code removed for readability */
});
and
//AJAX function to update page if hash changes
function initializeFromUrl(fromLink) {
/* code removed for readability */
//take hash from function call or from the URL if not
input = fromLink || window.location.hash ;
//remove # from hash
output = input.replace("#","");
//get the URL of the AJAX content for new page
pageId = output;
var url = $(this).attr('href'),
image = new Image();
image.src = url;
var clickedLink = $(this).attr('id');
location.hash = clickedLink;
image.onload = function () {
$('#content').empty().append(image);
};
image.onerror = function () {
$('#content').empty().html('That image is not available.');
}
$('#content').empty().html('Loading...');
}
[EDIT :] Here is the full code for your page that should work, provided you can create a page that just outputs the image's location from the database.
var recentHash = "";
var image_url ="";
$(document).ready(function() {
$('a.photo').click(function (event) {
var clickedLink = $(this).attr('id');
location.hash = clickedLink;
event.preventDefault();
});
setInterval('pollHash()',100);
});
function pollHash() {
//exit function if hash hasn't changed since last check
if (window.location.hash==recentHash) {
return;
}
//hash has changed, update recentHash for future checks
recentHash = window.location.hash;
//run AJAX to update page using page identfier from hash
initializeFromUrl(recentHash.substr(1));
}
//AJAX function to update page if hash changes
function initializeFromUrl(fromLink) {
/* code removed for readability */
//take hash from function call or from the URL if not
input = fromLink || window.location.hash ;
//remove # from hash
output = input.replace("#","");
//get the URL of the AJAX content for new page
pageId = output;
if(pageId != ""){
var temp_url = 'http://whitecu.be/user/mountain/'+pageId+'.html';
$.get(temp_url, function(data) {
image_url = data;
image = new Image();
image.src = image_url;
image.onload = function () {
$('#content').empty().append(image);
};
image.onerror = function () {
$('#content').empty().html('That image is not available.');
}
$('#content').empty().html('Loading...');
});
}else{
window.location = "http://whitecu.be/user/mountain";
}
}