Squirrl Squirrl - 4 months ago 13x
jQuery Question

How do I allow get requests - 403 forbidden error

I'm making an ajax request to my images directory. This works well on localhost, but when I put it online I get a 403 (Forbidden) error. How do I allow get requests?

url: url,
success: function(data) {
var parser = new DOMParser(),
doc = parser.parseFromString(data, 'text/html');
var rows = doc.querySelector('table').querySelectorAll('tr');
for (var i=0;i<rows.length;i++) {
if (rows[i].children[2]) {
var img = rows[i].children[2].children[0].getAttribute("href");
if(img.match(/\.(jpeg|jpg|gif|png)$/) != null){
var html = '<li id="" style="background-image: url('+img+')"></li>';
$('#nikoSlider ul').append(html)
} else { console.log("This is not a valid image type: " + img) }

Can I use something like
header('Access-Control-Allow-Origin: *');
in a php file.


Your url is of the form http://primaryman.com/pare/assets/images/{{COLLECTION}}/slider/, and it's a path to a directory. According to one of your comments, you cannot access a directory using AJAX. Here is the simplest way to solve the problem:

Create a middle-man PHP script that returns a json-encoded array of all the image paths you need. Then in your AJAX success callback, cycle through the images and append them to the DOM. Since the COLLECTION part of the paths is variable, you need a way to always call this PHP script no matter what path is used. I suggest changing the url in your AJAX call to call the PHP script directly and feed it the collection you want. For example, if you're trying to access the royce or summit collections you would use

url: '/path/to/slider_images.php?collection=royce //<- or collection=summit

In your PHP script, you can find the originally requested url path with:

$path = "/pare/assets/images/$_GET[collection]/slider/"

You can then use that to get all image files in the matching directory (remember to only select files with image extensions), put them in an $images array and send them back to the browser with:

echo json_encode($images);

This solution (which you linked to earlier) has good code to get you started.