Han Han - 6 months ago 15
Ajax Question

AJAX call not succeeding in chrome extension

I'm trying to get the number of images from a directory on my server. I'm using PHP to figure out the number of images, and AJAX (in my chrome extension) to get the number of images from my external PHP file.

It is going through the success: function{} but is not running the the if(data){}. It also occasionally alerts the error, saying The following error occurred: error. How do I fix this?

main.js

...


(function ($) {
$(document).ready(function(e) {
$.ajax({
url: 'http://website.com/numberOfImages.php', // <== POINTS TO THE VALID URL OF THE PHP FILE THAT OUTPUTS THE NUMBER OF IMAGES...
dataType: "HTML",
cache: false,
type: "POST",

//HANDLE THE SUCCESS CASE FOR THE AJAX CALL
success: function (data, textStatus, jqXHR) {
if(data){
alert(data);
}
},

//HANDLE THE FAILURE CASE FOR THE AJAX CALL
error: function (jqXHR, textStatus, errorThrown) {
alert('The following error occurred: ' + textStatus, errorThrown);
},

//HANDLE THE EVENT-COMPLETE CASE FOR THE AJAX CALL
complete: function (jqXHR, textStatus) {
}
});
});
})(jQuery);


manifest.json

{
"name": "some name",
"description": "Add description",
"version": "1.0",
"permissions": [
"activeTab"
],
"chrome_url_overrides" : {
"newtab": "main.html"
},
"background": {
"scripts": ["jquery-2.2.3.min.js", "background.js"],
"persistent": false
},
"permissions": [
"activeTab",
"https://ajax.googleapis.com/",
"storage",
"tabs",
"http://*/*",
"https://*/*"
],
"browser_action": {
"default_title": "some title"
},
"manifest_version": 2
}


numberOfImages.php

<?php

$dir = "/home/some/directory";
$fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileCount = iterator_count($fi);

die($fileCount);

?>

Han Han
Answer

@PatrickEvans comment answered my question. Thanks.

My updated code:

<?php

    $dir        = "/home/some/directory";
    $fi         = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
    $fileCount  = iterator_count($fi);

    echo $fileCount;

?>