I have a piece of code like that:
$(function() {
var uploader1 = new plupload.Uploader({
runtimes : 'gears,html5,flash,silverlight,browserplus',
browse_button : 'pickfiles1',
container : 'container',
max_file_size : '10mb',
url : 'upload.php',
flash_swf_url : '/plupload/js/plupload.flash.swf',
silverlight_xap_url : '/plupload/js/plupload.silverlight.xap',
filters : [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
],
resize : {width : 320, height : 240, quality : 90}
});
uploader1.bind('Init', function(up, params) {
$('#filelist1').html("<div>Current runtime: " + params.runtime + "</div>");
});
$('#uploadfiles1').click(function(e) {
uploader1.start();
e.preventDefault();
});
uploader1.init();
uploader1.bind('FilesAdded', function(up, files) {
var temp_img_name = '';
$.each(files, function(i, file) {
$('#filelist1').append(
'<div id="' + file.id + '">' +
file.name + ' (' + plupload.formatSize(file.size) + ') <b></b> <input type="hidden" name="hdnPictureNameAddtemp" value="' + file.name + '"/>' +
'</div>');
if(temp_img_name == ''){
temp_img_name += file.name;
} else {
temp_img_name += ', ' + file.name;
}
});
$('#filelist1').append('<input type="hidden" name="hdnPictureNameAdd" value="' + temp_img_name + '"/>');
up.refresh(); // Reposition Flash/Silverlight
});
uploader1.bind('UploadProgress', function(up, file) {
$('#' + file.id + " b").html(file.percent + "%");
});
uploader1.bind('Error', function(up, err) {
$('#filelist1').append("<div>Error: " + err.code +
", Message: " + err.message +
(err.file ? ", File: " + err.file.name : "") +
"</div>"
);
up.refresh(); // Reposition Flash/Silverlight
});
uploader1.bind('FileUploaded', function(up, file) {
$('#' + file.id + " b").html("100%");
});
});
My problem is that I want to create a loop because some parts of the code above needs to be changed. In fact, uploader1, filelist1, pickfiles1, uploadfiles1 should be changed. Its last number should increase from 1 to n. I tried every thing to create a loop but it seems not work.
Also, this code is used to control the PLupload
Did not go through the whole logic, but one option should (roughly) be something like this (for 10 uploaders), concatenating the itemIndex to each selector. (watch out for the container item which does not seem to be indexed)
Server side, you may encounter the need to know which uploader triggered the upload. This might be solved, for example, with querystring parameters.
$(function() {
for (var itemIndex=1, itemIndex<10; itemIndex++)
initUploader(itemIndex);
});
function initUploader(itemIndex) {
var uploader1 = new plupload.Uploader({
runtimes : 'gears,html5,flash,silverlight,browserplus',
browse_button : 'pickfiles'+itemIndex,
container : 'container'+itemIndex,
max_file_size : '10mb',
url : 'upload.php',
flash_swf_url : '/plupload/js/plupload.flash.swf',
silverlight_xap_url : '/plupload/js/plupload.silverlight.xap',
filters : [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
],
resize : {width : 320, height : 240, quality : 90}
});
uploader1.bind('Init', function(up, params) {
$('#filelist'+itemIndex).html("<div>Current runtime: " + params.runtime + "</div>");
});
$('#uploadfiles'+itemIndex).click(function(e) {
uploader1.start();
e.preventDefault();
});
uploader1.init();
uploader1.bind('FilesAdded', function(up, files) {
var temp_img_name = '';
$.each(files, function(i, file) {
$('#filelist'+itemIndex).append(
'<div id="' + file.id + '">' +
file.name + ' (' + plupload.formatSize(file.size) + ') <b></b> <input type="hidden" name="hdnPictureNameAddtemp" value="' + file.name + '"/>' +
'</div>');
if(temp_img_name == ''){
temp_img_name += file.name;
} else {
temp_img_name += ', ' + file.name;
}
});
$('#filelist'+itemIndex).append('<input type="hidden" name="hdnPictureNameAdd" value="' + temp_img_name + '"/>');
up.refresh(); // Reposition Flash/Silverlight
});
uploader1.bind('UploadProgress', function(up, file) {
$('#' + file.id + " b").html(file.percent + "%");
});
uploader1.bind('Error', function(up, err) {
$('#filelist'+itemIndex).append("<div>Error: " + err.code +
", Message: " + err.message +
(err.file ? ", File: " + err.file.name : "") +
"</div>"
);
up.refresh(); // Reposition Flash/Silverlight
});
uploader1.bind('FileUploaded', function(up, file) {
$('#' + file.id + " b").html("100%");
});
}
Related
On main page have Gallery, on click a image need open lightGallery slideshow with images that found on ftp directory, with gallery name that clicked on main page.
PHP for finding images and count it:
<?php
header("Content-Type: application/json");
$dirname = $_POST["galleryName"];
$imgGallery = glob("../gallery/" . $dirname . "/".$dirname."_*.*");
$thumbGallery = glob("../gallery/" . $dirname . "/thumb_*.*");
$countImages = count($imgGallery);
echo json_encode(array("imgNormal" => $imgGallery, "imgThumb" => $thumbGallery, "imgCount" => $countImages));
?>
JS:
$('.info').click(function() {
var galleryName = $(this).closest('.imgGallery').find('img.img-thumbnail').attr('name');
$.ajax({
url: "gallery/imgFinder.php",
dataType: "json",
type: "post",
data: {
galleryName: galleryName
},
success: function(xhr) {
if (xhr.imgCount != 0) {
console.log(xhr.imgNormal);
console.log(xhr.imgThumb);
console.log(xhr.imgCount);
for (var i = 1; i <= xhr.imgCount; i++) {
$(this).lightGallery({
dynamic: true,
dynamicEl: [{ //We need to create as much as we received w "xhr.imgCount"
"src": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg",
"thumb": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg"
}]
})
return;
}
} else {
console.log('Gallery \'' + galleryName + '\' has no images');
return;
}
},
error: function(xhr) {
console.error("Some error found");
}
});
});
We need to create as much dynamicEl with image/thumb variables, as we received xhr.imgCount
To get something like this:
dynamicEl: [{
"src": '...',
'thumb': '...'
}, {
'src': '...',
'thumb': '...'
}, {
'src': '...',
'thumb': '...'
}, {
'src': '...',
'thumb': '...'
}]
inside your JS code you needs to be updated something like below:
if (xhr.imgCount != 0) {
console.log(xhr.imgNormal);
console.log(xhr.imgThumb);
console.log(xhr.imgCount);
var dynamicEls = [];
for (var i = 0; i <= xhr.imgCount; i++) {
dynamicEls[i] = {
"src": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg",
"thumb": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg"
};
}
dynamicEls.pop(); //For remove unrealized last url/data
$(this).lightGallery({
dynamic: true,
dynamicEl: dynamicEls
});
}
So, I am using and temp variable dynamicEls and after the loop filling it in correct position.
I'm trying to recieve data in JSON from online php code, I'm getting undefined error
The website i'm retrieving from is https://www.orba.com.ng/getemployees.php
I'm using jQuery
localStorage['serviceURL'] = "https://www.orba.com.ng/";
var serviceURL = localStorage['serviceURL'];
var scroll = new iScroll('wrapper', { vScrollbar: false, hScrollbar:false, hScroll: false });
var employees;
$(window).load(function() {
setTimeout(getEmployeeList, 100);
});
function getEmployeeList() {
$('#busy').show();
$.getJSON(serviceURL + 'getemployees.php', function(data) {
$('#busy').hide();
$('#employeeList li').remove();
employees = JSON.parse(data.items);
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
'<img src="img/' + employee.picture + '" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + ' ' + employee.lastName + '</p>' +
'<p class="line2">' + employee.title + '</p>' +
'<span class="bubble">' + employee.reportCount + '</span></a></li>');
});
setTimeout(function(){
scroll.refresh();
});
});
}
$(document).ajaxError(function(event, request, settings, thrownError) {
$('#busy').hide();
alert("Failed: " + thrownError.error);
});
I'm getting error code undefined
It was a CORS issue, Quite easy to fix. Search on google
I'm using plupload to upload images in a form. When I press submit, the uploader.php does it job by uploading the images and processing the other form data using the multipart_params og pluploader.
However, I want to submit the form as well when no image is selected. When I submit with no image selected now, uploader.php simply doesn't run.
Is there a way to run uploader.php in all cases, even with no files selected?
Thanks.
This is the simplified code I'm working on:
<textarea id="textarea_input"></textarea>
<label id="browse" href="javascript:;">
<i class="fa fa-camera"></i> Add image
<span id="filelist"></span>
</label>
<a id="start-upload" href="javascript:;"">Add</a>
<span id="console"></span>
<script type="text/javascript">
var uploader = new plupload.Uploader({
browse_button: 'browse', // this can be an id of a DOM element or the DOM element itself
url: 'uploader.php',
multi_selection: false,
resize: {
width: 1500,
height: 1500,
quality: 30
},
filters: {
mime_types : [
{ title : "Image files", extensions : "jpg,gif,png,jpeg" }
],
max_file_size: "10mb",
prevent_duplicates: true
},
multipart_params : {
"textarea_input" : "value1" //predefine textarea_input here, uploader right before uploader.start()
}
});
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
while (up.files.length > 1) { //custom: limit to 1 file upload.
up.removeFile(up.files[0]);
document.getElementById('filelist').innerHTML = '';
}
var html = '';
plupload.each(files, function(file) {
html += '<br /><span id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></span>';
});
document.getElementById('filelist').innerHTML += html;
});
uploader.bind('UploadProgress', function(up, file) {
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
});
uploader.bind('Error', function(up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
});
uploader.bind('UploadComplete', function(up, files) {
window.location = "mobilelogbook.php?saved=2";
});
document.getElementById('start-upload').onclick = function() {
uploader.settings.multipart_params["textarea_input"] = document.getElementById("textarea_input").value;
uploader.start();
};
</script>
And the uploader.php:
<?php
if (empty($_FILES) || $_FILES["file"]["error"]) {
$fileName = '';
} else {
$fileName = $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], "images/logbook/$fileName");
}
if (isset($_POST['textarea_input'])) {
$log = $_POST['textarea_input'];
} else {
$log = '';
}
// SQL GOES HERE: ADDS THE TEXTAREA_INPUT AND FILENAME TO A TABLE.
die('{"OK": 1}');
?>
I want to replace the whole item inside the id div instead of adding it.I am not familliar with javascript/ajax/jquery and i dont know which file i will edit.
This is the sample code given by pusher.com in activity-stream tutorial
$(function() {
var pusher = new Pusher('pusher key');
var channel = pusher.subscribe('site-activity');
var streamer = new PusherActivityStreamer(channel, '#replace_item');
});
html id that will replace all item inside the div
<div id="replace_item">ITEMS</div>
This is the javascript function
function PusherActivityStreamer(activityChannel, ulSelector, options) {
var self = this;
this._email = null;
options = options || {};
this.settings = $.extend({
maxItems: 10
}, options);
this._activityChannel = activityChannel;
this._activityList = $(ulSelector);
this._activityChannel.bind('activity', function(activity) {
self._handleActivity.call(self, activity, activity.type);
});
this._activityChannel.bind('page-load', function(activity) {
self._handleActivity.call(self, activity, 'page-load');
});
this._activityChannel.bind('test-event', function(activity) {
self._handleActivity.call(self, activity, 'test-event');
});
this._activityChannel.bind('scroll', function(activity) {
self._handleActivity.call(self, activity, 'scroll');
});
this._activityChannel.bind('like', function(activity) {
self._handleActivity.call(self, activity, 'like');
});
this._itemCount = 0;
};
PusherActivityStreamer.prototype._handleActivity = function(activity, eventType) {
var self = this;
++this._itemCount;
var activityItem = PusherActivityStreamer._buildListItem(activity);
activityItem.addClass(eventType);
activityItem.hide();
this._activityList.prepend(activityItem);
activityItem.slideDown('slow');
if(this._itemCount > this.settings.maxItems) {
this._activityList.find('li:last-child').fadeOut(function(){
$(this).remove();
--self._itemCount;
});
}
};
PusherActivityStreamer.prototype.sendActivity = function(activityType, activityData) {
var data = {
activity_type: activityType,
activity_data: activityData
};
if(this._email) {
data.email = this._email;
}
$.ajax({
url: 'php/trigger_activity.php', // PHP
// url: '/trigger_activity', // Node.js
data: data
})
};
PusherActivityStreamer._buildListItem = function(activity) {
var li = $('<li class="activity"></li>');
li.attr('data-activity-id', activity.id);
var item = $('<div class="stream-item-content"></div>');
li.append(item);
var imageInfo = activity.actor.image;
var image = $('<div class="image">' +
'<img src="' + imageInfo.url + '" width="' + imageInfo.width + '" height="' + imageInfo.height + '" />' +
'</div>');
item.append(image);
var content = $('<div class="content"></div>');
item.append(content);
var user = $('<div class="activity-row">' +
'<span class="user-name">' +
'<a class="screen-name" title="' + activity.actor.displayName + '">' + activity.actor.displayName + '</a>' +
//'<span class="full-name">' + activity.actor.displayName + '</span>' +
'</span>' +
'</div>');
content.append(user);
var message = $('<div class="activity-row">' +
'<div class="text">' + activity.body + '</div>' +
'</div>');
content.append(message);
var time = $('<div class="activity-row">' +
'<a href="' + activity.link + '" class="timestamp">' +
'<span title="' + activity.published + '">' + PusherActivityStreamer._timeToDescription(activity.published) + '</span>' +
'</a>' +
'<span class="activity-actions">' +
'<span class="tweet-action action-favorite">' +
'<span><i></i><b>Like</b></span>' +
'</span>' +
'</span>' +
'</div>');
content.append(time);
return li;
};
If you want to replace the entire div instead of adding things to it, I think this will work.
Change
this._activityList.prepend(activityItem);
for
this._activityList.empty();
this._activityList.prepend(activityItem);
".prepend" adds the activityItem to the top of the div as you know, but ".empty()" will clear everything previously in the div before you do this.
I have a jQuery script that returns JSON data and for some reason a specific value is not displayed and I don't know why since all the other properties are displayed fine. The value that is not working correctly is data.code.
$(document).ready(function() {
$(".cos").click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
var produs_href = $(this).closest('.productinfo').find('a:first').attr('href');
var id_prod = $(this).data('id');
var color = $(this).closest(".col-sm-4").find(".selected").data("color");
if (typeof color === 'undefined') {
alert ("selecteaza o culoare!");
} else {
$.getJSON(href + '&color=' + color).done(function(data) {
$.each(data, function(key, val) {
$("#cnt").empty();
$("#cnt").append('' + val.cnt + '');
$.ajax({
url: "/engine/shop/produse_cos_popup.php?id=" + id_prod + "&color=" + color,
type: "GET",
datatype: 'json',
success: function(data) {
$('#qty').html('Cantitate: ' + data.qty + '');
$('.nr_prod').html('' + data.qty_total + 'produse în cosul dvs');
$('#nume').html('' + data.nume + '');
$('#pret').html('' + data.pret_total + '');
if (data.poza!='') {
$('.produs_img').html(data.poza);
} else {
$('.produs_img').html('<img class="img-responsive" src="/images/no_photo.jpg">');
}
$('#cod').html('<b>Cod Produs:</b ' + data.code + '');
$('#culoare').html('<b>Culoare:</b> ' + data.culoare + '');
$('#greutate').html('<b>Greutate:</b> ' + data.greutate +'');
$('#viteza').html('<b>Viteza maximă:</b> ' + data.viteza + '');
$('#autonomie').html('<b>Autonomie:</b> ' + data.autonomie + '');
$('#putere').html('<b>Putere motor:</b> ' + data.putere + '');
$('#detalii_prod').modal('show');
}
});
});
});
}
});
});
Here is the JSON returned. As you can see the variable code is there. It displays `Cod Produs: but without the value.
{
"qty": "4",
"poza": "<img class=\"img-responsive\" src=\"images\/trotineta_verde.png\">",
"id": "1",
"nume": "Eco",
"code": "etw1",
"greutate": "10.7 kg",
"viteza": "27 km\/h",
"autonomie": "30 km",
"putere": "350 Watt",
"culoare": "verde",
"pret_total": "37560",
"qty_total": "18"
}
You are not closing the </b
Change
$('#cod').html('<b>Cod Produs:</b ' + data.code + '');
For
$('#cod').html('<b>Cod Produs:</b> ' + data.code + '');