Limit the number of uploads in plupload - javascript

My client is using an old classipress version, here's a github repo I found but what he's using is much older. Running the latest Wordpress version. It comes with plupload, some old version, couldn't find the version in the theme. Here's Functions.php, here's plupload. Here's the html of my page, no need to see it, but i'm putting it there because the page is protected so that's the only way to inspect the whole code if you want to.
I want to add the ability to upload multiple pictures at the same time, to do that, I add this to functions.php
add_filter('appthemes_plupload_config', 'enable_plupload_multisel', 10 ,1);
function enable_plupload_multisel($app_plupload_config){
$app_plupload_config['plupload']['multi_selection'] = true;
return $app_plupload_config; }
But I don't know how to stop the user from uploading more than 8 pictures? I tried adding max_files and max_files_count and max_file_count and nothing worked, I even modified the source code of the plugin itself and the js and nothing worked. I want to stop the user from being able to upload more than 8 images.
After I gave up on plupload, I tried doing it using Jquery, again didn't work
/* prevent form submission if user selects more than 8 pics */
jQuery('#app-attachment-upload-pickfiles').change(function() {
if (this.files.length > 8) {
alert('Uploading more than 8 images is not allowed');
this.value = '';
}
});
// Prevent submission if limit is exceeded.
jQuery('#mainform').submit(function() {
if (this.files.length > 8) {
jQuery('#app-attachment-upload-pickfiles').hide();
jQuery('#step1').hide();
return false;
} else {
jQuery('#app-attachment-upload-pickfiles').show();
jQuery('#step1').show();
}
});
Edit
My pluploadjs here. FilesAdded
attachUploader.bind('FilesAdded', function(up, files) {
jQuery.each(files, function(i, file) {
jQuery('#app-attachment-upload-filelist').append(
'<div id="' + file.id + '" class="app-attachment-upload-progress">' +
file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>' +
'</div>');
window.appFileCount += 1;
APP_Attachment.hideUploadBtn();
});
up.refresh();
attachUploader.start();
});
I modified it to look like so
attachUploader.bind('FilesAdded', function(up, files) {
var maxfiles = 8;
if(up.files.length > maxfiles )
{
up.splice(maxfiles);
alert('no more than '+maxfiles + ' file(s)');
}
if (up.files.length === maxfiles) {
$('#app-attachment-upload-filelist').hide("slow"); // provided there is only one #uploader_browse on page
}
jQuery.each(files, function(i, file) {
jQuery('#app-attachment-upload-filelist').append(
'<div id="' + file.id + '" class="app-attachment-upload-progress">' +
file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>' +
'</div>');
window.appFileCount += 1;
APP_Attachment.hideUploadBtn();
});
up.refresh();
attachUploader.start();
});
Is that all? Will it work now? I haven't tested it because it will give errors

I'm not sure but your code should almost work. I think you should manually remove the files from the queue by calling the removeFile method.
Maybe try this code:
attachUploader.bind('FilesAdded', function(up, files) {
var maxfiles = 8;
// remove all new files after the max of files
jQuery.each(up.files, function(i, file) {
if(i > maxfiles){
up.removeFile(file);
}
});
});

Related

looking to Work around the 403 error with php script

I have been using JavaScript to retrieve my images from a directory and on local-host this works just fine but now I am running it on a remote sever I get the 403 Forbidden Error, I know why this is but I am looking for a way around it, keeping my Java functioning much the same, so I was thinking if I put an index.php in the gallery folder and called it with a path and have it return a file list back to my JavaScript and a lough it to carry on.
How would I go about this as I am not very good with PHP at the moment? Thanks.
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
var dir_path = $(this).data("albumid");
LoadGallery(dir_path);
return false;
});
});
function LoadGallery(dir_path) {
$.ajax({
url: dir_path,
success: function(data) {
$(".image-container").empty();
$(data).find("a:contains(.jpg), a:contains(.png), a:contains(.jpeg)").each(function() {
this.href.replace(window.location.host, "").replace("http:///", "");
var file = dir_path + $(this).text();
$(".image-container").append($("<a href='javascript:;' class='thumb' data-src='" + file + "'><img src='" + file + "' title='Click to enlarge' alt='#'/></a>"));
if ($(".image-container").children("a").length === 30) {
return false;
}
});
$(".image-container").append("<strong><p>Click on a thumb nail to show a larger image.</p></strong>");
$(".thumb").bind('click', function() {
var Popup = "<div class='bg'></div>" + "<div class='wrapper'><img src='<img src=''/>" + "<label href='javascript:;' class='prev-image'>«</label><label href='javascript:;' class='next-image'>»</label><a href='javascript:;' class='close' title='Close'>Close</a>";
var Img = $(this).attr("data-src");
$("body").prepend(Popup);
$(".bg").height($(window).height() * 4);
$(".wrapper img").attr("src", Img);
$(".prev-image").bind('click', function() {
var prev = $(".image-container").find("img[src='" + Img + "']").parent().prev('a').find("img").attr('src');
if (!prev || prev.length === 0)
return false;
else {
$(".wrapper img").attr("src", prev);
Img = prev;
}
});
$(".next-image").bind('click', function() {
var next = $(".image-container").find("img[src='" + Img + "']").parent().next('a').find("img").attr('src');
if (!next || next.length === 0)
return false;
else {
$(".wrapper img").attr("src", next);
Img = next;
}
});
$(".close").bind('click', function() {
$(this).siblings("img").attr("src", "")
.closest(".wrapper").remove();
$(".bg").remove();
});
});
}
});
}
</script>
Original why are you getting the 403 error? returning a file(name) list from php to your scripts probably isn't going to work around this error, because the javascript would ultimately be making the same request.
on the other hand if you know that you have access to the image files from the server-side there are a few things you could do, like return the binary value of the image (javascript can take this) or generating a close of the file.
Update
if the server allows it, you can use the exec command in php to return a list of files from the directory: eg
\<\
<?php
jpgs = exec('ls /your_directory_here');
echo json_encode(jpgs);
?>
if they don't allow exec(), which they might not, you could try...
http://www.w3schools.com/php/func_directory_readdir.asp
does that help?

how do I remove an item that is set to upload?

I have created an uploader using javascript and php. The problem is that I only want to allow specific file types. I have it letting the user know the file is not valid but I am not sure how to remove the file from being uploaded. Can anyone tell me how to remove the upload?
multiUploader.prototype._preview = function(data) {
this.items = data;
if (this.items.length > 0) {
var html = "";
var uId = "";
for (var i = 0; i < this.items.length; i++) {
uId = this.items[i].name._unique();
if (typeof this.items[i] != undefined) {
if (self._validate(this.items[i].type) <= 0) {
var errorClass = '<h3 class="text-danger">Invalid file format' + this.items[i].name + '</h3>'
jQuery(".errorContent").append(errorClass);
jQuery.remove(this.items[i]);
}
html += '<div class="dfiles" rel="' + uId + '"><h5>' + this.items[i].name + '</h5><div id="' + uId + '" class="progress" style="display:none;"></div></div>';
}
}
jQuery("#dragAndDropFiles").append(html);
}
}
This is not all of the code, just the function that displays my error message and also shows the uploaded file on the page. I tried it with jQuery.remove but it does not work. Any ideas are appreciated
what is a "file type"? I could send you a .php file that ends in .jpg, would you accept that? (I hope not!). Let the user upload the files with a warning that files X, Y, Z are not going to be accepted based on extension mismatch. Then actually test their content to see if the files are truly what their extension claims, because -and this part is important- your javascript in no way guarantees that what you're going to get is what you wrote your scripts to allow. Changing your script in my browser is a matter of opening my devtools and rewriting your script, then hitting ctrl-s. Now my browser will be running my code, not your code, and happily upload my files anyway.
Always, always, server-verify the user data.

Use Javascript to scan a local directory and then update an Anchor tag with the "latest" file

I'm trying to create a simple HTML page that will basically, load up some javascript, and check my direction (../Files)
the Files folder contains
file_001.txt
file_002.txt
file_003.txt
I then want javascript to use the latest one (file_003.txt), and update a anchor tag with the id of "file_download".
Would anyone by any chance have an idea how to do this?
The reason is, lets say I have a terms and conditions PDF file that is T&C_001.pdf and download the line a new terms and conditions is released. so we keep the T&C_001.pdf for any old records and we upload T&C_002.pdf. Now this will not need any HTML knowledge or even Javascript. The owner of the site would just need to add a new file with 002 on the end.
though, not fully accurate, you could try
<script type="text/javascript">
function getLatest(location, filename, ext, readyCallback, index) {
var tgIndex = typeof index === 'undefined' ? 1 : index;
$.ajax({
type: 'HEAD',
url: location + '/' + filename + '-' + index + '.' + ext,
success: function() {
getLatest(location, filename, ext, readyCallback, tgIndex + 1);
},
error: function() {
if (tgIndex > 1) {
readyCallback(location + '/' + filename + '-' + (tgIndex-1) + '.txt');
return;
}
readyCallback();
}
});
}
getLatest('linkToSite', 'file', 'txt', function(filename) {
if (typeof filename === 'undefined') {
alert('No file found on the location');
}
// do something with returned filename
});
</script>
which would try to check if the file is there, when not the previous index was the latest one. If the first one fails, there is no file on the specified location
This reply doesn't add formatting, and rather expects the files as:
- file-1.txt, file-2.txt, ...
this example assumes jquery :)
a fiddle of it you can find here
http://jsfiddle.net/Icepickle/JL5Su/

memory leak in IE9

I seem to have a memory leak in IE9. It works just fine in Chrome. The memory leak is on the client machine. I left this page open for days in chrome and no leak.
Using jquery 1.9.0, signalr rc2
This page uses signalr and refreshes it's contents every 5 seconds with what comes from the server.
I have four tabs/divs that do this.
proxy.on('newRequests', function (data, updatetime) {
newrequestupdatetime.text('Last updated: ' + updatetime);
numberofnewrequests.text('Number of cases found: ' + data.length);
numberofnewrequeststab.text('(' + data.length + ')');
var h = '';
$.each(data, function (i, val) { h += '<li>' + val.Ref + ' ' + val.Type + '</li>'; });
newrequests.html(h);
});
newrequests is an ul on the page which I initialized like this
var newrequests = $('#newrequests');
in
$(function () {});
Not really sure what is the cause.
I can make it a lot worse by doing this.
newrequests.empty();
$.each(data, function (i, val) { newrequests.append('<li>' + val.Ref + ' ' + val.Type + '</li>'); });
I'm guessing that it has something to do with the last line of code, that puts the new html inside the ul tag.
Try changing the line into this (old code):
document.getElementById('newrequests').innerHTML = h;
See also: jQuery - Internet Explorer memory leaks

Cannot get json results from twitter using PhoneGap and jQuery

I'm trying to get the last 50 tweets using a certain hash tag, on a mobile device using PhoneGap (0.9.6) and jQuery (1.6.1). Here's my code:
function getTweets(hash, numOfResults) {
var uri = "http://search.twitter.com/search.json?q=" + escape(hash) + "&callback=?&rpp=" + numOfResults;
console.log("uri: " + uri);
$.getJSON(uri, function(data) {
var items = [];
if(data.results.length > 0) {
console.log("got " + data.results.length + " results");
$.each(data.results, function(key, val) {
var item = "<li>";
item += "<img width='48px' height='48px' src='" + val.profile_image_url + "' />";
item += "<div class='tweet'><span class='author'>" + val.from_user + "</span>";
item += "<span class='tweettext'>" + val.text + "</span>";
item += "</div>";
item += "</li>";
items.push(item);
});
}
else {
console.log("no results found for " + hash);
items.push("<li>No Tweets about " + hash + " yet</li>");
}
$("#tweetresults").html($('<ul />', {html: items.join('')}));
});
}
This code works great in a browser, and for a while worked in the iPhone simulator. Now it's not working on either the iPhone or Android simulator. I do not see any of the console logs and it still works in a browser.
What am I doing wrong? If it's not possible to call getJson() on a mobile device using PhoneGap, what is my alternative (hopefully without resorting to native code - that would beat the purpose).
Bonus: how can I debug this on a mobile simulator? In a browser I use the dev tools or Firebug, but in the simulators, as mentioned, I don't even get the log messages.
As always, thanks for your time,
Guy
Update:
As #Greg intuited, the function wasn't called at all. Here's what I found and how I bypassed it:
I have this <a> element in the HTML Get tweets
Then I have this code in the $(document).ready() function:
$("#getTweets").click(function() {
var hash = "#bla";
getTweets(hash, 50);
});
That didn't call the function. But once I changed the code to:
function gt() {
var hash = "#bla";
getTweets(hash, 50);
}
and my HTML to:
Get Tweets
it now works and calls Twitter as intended. I have no idea what's screwed up with that particular click() binding, but I ran into similar issues with PhoneGap before. Any ideas are appreciated.
Considering that (a) there isn't much that could go wrong with the first line of your function and (b) the second line is a log command, then it would seem that the function isn't being called at all. You'll have to investigate the other code in your app.
Or are you saying that you don't have a way to read logged messages on your mobile devices?

Categories

Resources