looking to Work around the 403 error with php script - javascript

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?

Related

Can Anybody Explain Why This Script Cannot Be Uploaded as an External Resource?

I am currently working within Tumblr's theme builder framework, and have been facing some difficulties uploading certain scripts as external resources. Upon several upload attempts, I continuously received an error message implying that Tumblr does not accept .html files to be uploaded as an asset, even though the file I am attempting to upload is a .js file.
I suppose it's worth noting that my site runs via HTTPS, so why would a code, (as shown below), not be able to be loaded as an external source/asset?
UPDATE: Ok, so far the issue has something to do with this portion of HTML in the script:
if (photos[j].alt_sizes[1]) {
imgURL = photos[j].alt_sizes[1].url;
// console.log(imgURL, linkURL);
} else {
continue;
}
$("#tumblr-posts").append(
"<li><a href=" +
linkURL +
"><img src=" +
imgURL +
" /></a>" +
"</li>"
);
}
The denied external JS (mycustomscript.js):
apiKey = "API-HIDDEN";
limit = 4;
$.ajax({
url: "https://api.tumblr.com/v2/blog/MYTUMBLRID.tumblr.com/posts?limit=4",
dataType: "jsonp",
data: {
api_key: apiKey,
tag: "blog"
},
success: function(results) {
var i = 0;
while (i < results.response.posts.length) {
var type = results.response.posts[i].type;
if (type == "photo") {
var photos = results.response.posts[i].photos;
var linkURL = results.response.posts[i].post_url;
var caption = results.response.posts[i].caption;
for (var j = 0; j < photos.length; j++) {
if (photos[j].alt_sizes[1]) {
imgURL = photos[j].alt_sizes[1].url;
// console.log(imgURL, linkURL);
} else {
continue;
}
$("#tumblr-posts").append(
"<li><a href=" +
linkURL +
"><img src=" +
imgURL +
" /></a>" +
"</li>"
);
}
}
i++;
}
console.log(results.response);
}
});
How I've attempted to call for the script, (x's in place to conceal hidden link portions):
<script src="http://static.tumblr.com/x/x/mycustomscript.js"></script>
It’s due the HTML tags in the script. You can work around this by splitting the HTML tags so
"<li>"
Becomes
"<"+"li>"
And do the same with end tags too.

Limit the number of uploads in plupload

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);
}
});
});

Keycode trigger on enter key not functioning correctly

I'm using keycode to trigger a button click on enter. I have the following, which is working when an alert is placed in they keycode function, but not when placed in the .click(function.... Not sure what I'm missing to get the keycode to trigger the ajax call. It is currently just pushing ?imageid=750 to the end of the query string in the URL.
//force use of only numerical input
$('#imageid').keyup(function (event) {
this.value = this.value.replace(/[^0-9\.]/g, '');
if (event.keyCode == 13) {
alert($("#imageid").val());
//event.preventDefault();
$('.image-search').trigger('click');
}
});
$('.image-search').click( function () {
var root = "http://localhost:7777/proxy/staging/rest/v1/cms/story/id/";
//CLEAR IMAGE ID VALUE FROM PREVIOUS ENTRIES
$("#imageid").val('');
var encodeID = $("#imageid").val();
var bearerToken = localStorage.getItem('Authorization');
//IF TESTING ON LOCALHOST
if (document.domain == 'localhost') {
url = root + encodeID + "/images";
} else {
//IF IN PRODUCTION
url = "/cropper/admin/cropv2/rest/v1/cms/story/id/" + encodeID + "/images";
//GRAB REFERRER URL FOR ASSET ID
//STRIP OUT ASSET ID, MATCH BUT DON'T INCLUDE 'ASSETS' AND SET SUCCESEEDING VALUE AS ASSET ID
var regexp = /assets\/(\d+)/;
var assetid = regexp.exec(window.document.referrer);
$("#imageid").val(assetid[1]);
};
$.ajax({
url: url,
method: 'GET',
headers: {
"Authorization": bearerToken
},
}).then(function (response) {
var obj = response;
$("#imageid").css("border-color", "#ccc");
$(".search-results").empty();
for (var property in obj.entity.entries) {
if (obj.entity.entries.hasOwnProperty(property)) {
$(".search-results").append($("<li><a href='" + obj.entity.entries[property].uri + "' target='_blank'><div class='thumbnail'><img width='30' height='30' src='" + obj.entity.entries[property].uri + "' target='_blank'/></img><div class='caption'><p>" + obj.entity.entries[property].orientation + "</p></div></a></li>"));
}
}
//$(".search-results").append("<div class='caption'>" + data.id + "</div><div class='thumbnail'><img width='40' height='40' src='" + data.thumbnailUrl + "'/></img>").css("float", "left");
}).fail(function (data) {
$(".search-results").empty();
$(".search-results").append("<p class='alert alert-danger'>Invalid ID</p>");
$("#imageid").css("border-color", "red");
});
});
});
But when implemented into the full project, it no longer works correctly. I'm not sure what I'm missing here.
Using this fiddle: JSFIDDLE, and removing lines 1-173, the trigger works correctly. With the lines included, it seems to be blocked.
Your code is working fine, you are having other Javascript errors present that are causing the script to stop.
Also Try $('.image-search').click(); instead of $('.image-search').trigger('click');
Uncaught ReferenceError: ImglyKit is not defined
Uncaught TypeError: Cannot read property 'addEventListener' of null (fileInput)

Parsing links from an XML files with JavaScript

To display my latest blog-posts on a different page I want to parse the rss-feed from the blog and then generate elements with it.
I first tried to parse a fixed .xml file for which I wrote the following code:
var maxBlogposts = 5;
var blogPosts = 0;
$.get("rss.xml", function(data) {
$(data).find("item").each(function() {
if(blogPosts === maxBlogposts) return;
var el = $(this);
//Only display 3 posts on small devices.
var extra = (blogPosts >= 3) ? "not-small 12u(small)" : "12u(small)";
var div = $('<div class="6u ' + extra + '" class="blog-entry"></div>');
var h = $('<h4>' + el.find("title").text() + '</h4>');
var description = el.find("description").text().replace('[…]', '[…]');
var p = $('<p>' + description + '</p>');
div.append(h);
div.append(p);
$('#blog').append(div);
blogPosts++;
});
});
This worked perfectly fine. Now I want to parse the actual rss-feed. For this I wrote a PHP script which simply gets the feed and echos it.
<?php
$rss = file_get_contents('http://xn--der-grne-baum-1ob.net/feed/');
die($rss);
?>
And again I get the correct XML file on the frontend.
The problem I have is that now my code is no longer working. Getting the description was failing as well as the links. I fixed the description by accessing
el.find(description")[0].innerHTML
However I can't seem to get the links to work. The data returned from the PHP file contains a node with the link in it. The "el"-element also contains children named "link" but those no longer contain the actual link.
I feel like the links may get "escaped" during parsing? At least that is the only reason i could think of that would result in what I am observing.
The XML I am parsing comes from http://xn--der-grne-baum-1ob.net/feed/
Try
var maxBlogposts = 5
, blogPosts = 0;
$.get("https://query.yahooapis.com/v1/public/yql?q=select"
+ " * from feed where url='http://xn--der-grne-baum-1ob.net/feed/'")
.then(function(data) {
$(data.documentElement).find("results item")
.each(function() {
if(blogPosts === maxBlogposts) return;
var el = $(this);
//Only display 3 posts on small devices.
var extra = (blogPosts >= 3) ? "not-small 12u(small)" : "12u(small)";
var div = $('<div class="6u ' + extra + '" class="blog-entry"></div>');
var h = $('<h4>' + el.find("title").text() + '</h4>');
var description = el.find("description").text().replace('[…]', '[…]');
var p = $('<p>' + description + '</p>');
div.append(h);
div.append(p);
$('#blog').append(div);
blogPosts++;
});
}, function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="blog"></div>
See YQL Console

How do I change the list of uploaded files?

I am attempting to use XMLHttpRequest to upload files to the server. Here are the steps I would like the code to do:
List the file in a file list ul
Upload the file(s) while displaying a progress bar
When the file is completely uploaded, change the list item for that file to a link without the progress bar. This is where I am having a problem.
Here is the HTML code I am working with:
<h1>Upload Files</h1>
<input type='file' name='doc_upload_field[][]' multiple='multiple' id='doc_upload_field' />
<ul id='filelist'></ul>
Here is the javascript code I am working with:
function transferFailed(evt) {
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
alert("The transfer has been canceled by the user.");
}
var filelist = $('#filelist');//define where the list of files will go
var url = "/";
function handleFileSelect_inputfield(evt) {
var files = evt.target.files; // FileList object
// run through each file individually.
for (var i = 0, f; f = files[i]; i++) {
var li = $("<li><strong>" + f.name + "</strong> (" + f.type +") - " + f.size + " bytes <div class='progress_bar'><div class='percent'> </div></div></li>");
filelist.append(li);//put the file in the filelist
var formData = new FormData();
formData.append(f.name, f);
//upload through xmlhttprequest
var xhr = new XMLHttpRequest();
xhr.upload.li = li;
xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
var percentLoaded = Math.round((e.loaded / e.total) * 100);
// Increase the progress bar length.
if (percentLoaded < 100) {
this.li.find(".progress_bar").addClass('loading');
this.li.find(".percent").width(percentLoaded + '%');
}
}
}, false);
xhr.upload.addEventListener("load", function(e) {
//uploading is complete
}, false);
xhr.upload.addEventListener("error", transferFailed, false);
xhr.upload.addEventListener("abort", transferCanceled, false);
xhr.open('POST', url, true);
xhr.responseType = 'text';
xhr.onload = function(e) {
if (this.readyState==4){
if (this.status == 200) {
//console.log(this.response);
console.log("finished=" + li);//returns as an object
//console.log("filename=" + f.name);//error: cannot read property 'name' of undefined
//change the list item. Not working...
this.li.find("li").html("<a href='#'>" + f.name + "</a>");
}
}
};
xhr.send(formData); // multipart/form-data
}
}
document.getElementById('doc_upload_field').addEventListener('change', handleFileSelect_inputfield, false);
Everything seems to be working, but when I want to change the list item, li, it is not recognizing it. I am able to change the progress bar length by calling:
this.li.find(".progress_bar").addClass('loading');
this.li.find(".percent").width(percentLoaded + '%');
But when I want to change the list item:
this.li.find("li").html("<a href='#'>" + f.name + "</a>");
It does not work.
Does anyone know why it would find it when changing the progress bar, but not find it after it is uploaded?
The expression
this.li.find("li")
looks for an <li> element inside the other <li> element. There isn't one, so nothing happens.
I think that just
this.li.html("<a href='#'>" + f.name + "</a>");
should be what you want. Or you could just do this:
this.li = $("<li><a href='#'>" + f.name + "</a></li>");
edit oops no that won't work because you've stuck it in the DOM already. But the first one should work.
edit — you've also got a closure-related problem (or scope-related; whatever). What you can do is something like what you've already done for the "li" value. Add another property for it to "xhr.upload":
xhr.upload.updated_li = "<a href='#'>" + f.name + "</a>";
Do that right where you set "xhr.updated.li". Then, in the event handler, you can do:
this.li.html(this.updated_li);

Categories

Resources