Can't populate <div> with elements of a json_encoded php array - javascript

This function worked previously (the last time I opened this project over a week ago), but now I can't seem to get it to work at all and I have no idea how to figure out what's going wrong! First, I'll diagram my file architecture in case my file paths are incorrect and causing my php to not even be called:
~/Sites
proj1
htdocs
index.html
ajax.php
scripts
java_script.js
styles
style_sheet.css
includes
scrapedImages
.
.
.
Here's the JS function that uses AJAX to call a .php script:
function requestServer() {
$.getJSON('/Users/aweeeezy/Sites/proj1/htdocs/ajax.php', function(data) {
$.each(data, function(key, val) {
var html = "<img src='/Users/aweeeezy/Sites/proj1/includes/scrapedImages/"+val+"' style='display:block;max-width:20px;max-height:20px;width:auto;height:auto' alt=null />"
$('#puppy-box').prepend(html);
});
});
}
The line setting var html was <img src='...'+images[i]+"... when I first opened the project this morning, but I'm not sure why...I think because I was testing the site out, it was faster to only load a fraction of the images and used a for loop to cycle through only the first 10 or so pictures, hence the i index. Anyway, shouldn't it be data[i], or val[i]...or data[val]? I have no idea what's going on here.
Here's the ajax.php file that the JS function is trying to call:
<?php
$images = scandir('/Users/aweeeezy/Sites/proj1/includes/scrapedImages/');
/*foreach ($images as $key => $image) {
if ($image == '.' || $image == '..') {
unset($images[$key]);
}
}*/
echo json_encode($images);
?>
I commented out the middle part because I wasn't sure if this was causing a complication. I tried putting both echo and print lines in here to see if the script is being called, but even if they are working, I can't really see them because they're being returned as data (I think) to the JS function that calls the script.
How do I even go about debugging this mess and get my girlfriend's valentine's day project back on track!

Related

I am trying to include many HTML files into a specific DIV

I create HTML files of press articles as separate entities as they can appear in several places in the website. In one place I want the ability to display all articles for a particular year into a specific div Called "news".
I found the w3 schools include html code this is fine except it always displays the included HTML as a new window. I have tried several methods but no luck. Do you know what coding changes i would need to do in order to achieve my aim. I think I need a (Document.getelement by id) but cannot work out where to put the code.
enter code here
<!DOCTYPE html>
<html>
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
</script>
<body>
<div w3-include-html="content.html"></div>
<script>
includeHTML();
</script>
</body>
<html>
<!-- Content.html -->
Google Maps<br>
Animated Buttons<br>
Modal Boxes<br>
Animations<br>
Progress Bars<br>
Hover Dropdowns<br>
Click Dropdowns<br>
Responsive Tables<br>
</html>
I would advise against the JavaScript approach; and simply opt to render your cumulative pages at the server end, and then serve out the built-up HTML. Here's the elementary how-to.
The simplest thing to do would be to have a plain text file with all the articles for a given month listed. Suppose we put the following into indexes/Press2019.txt, one entry per line:
Apr20.html
Mar20.html
oct19.html
sept19.html
July19.html
...
Then, suppose we have a simple PHP file, press.php, as follows (please read the inline comments to understand what the code is doing):
<!DOCTYPE html>
<html lang="en">
<?php
// Validate the "year" request as a valid integer
$year = isset($_GET['year']) ? filter_var($_GET['year'], FILTER_VALIDATE_INT) : false;
empty($year) && die('Invalid Year!');
// Check if an index for the year exists
$path_index = "indexes/Press{$year}.txt";
!is_file($path_index) && die("No press index for year {$year}!");
// Load list of articles
$texts = file($path_index, FILE_IGNORE_NEW_LINES);
// Function for HTML title & header
function make_header($title) {
echo "<head><title>{$title}</title></head>";
echo "<body><h1>{$title}</h1>";
}
// Output header
make_header("All Press Articles for Year {$year}");
// Output all articles
foreach($texts as $file) {
$path = '/html/press/' . $file;
$html = file_get_contents($path);
$html = parse_body($html); // read below for explanation
echo $html;
?>
</body>
</html>
This would load and output all the articles in your list into one page.
I'm assuming that your individual articles are also static HTML files with <html>, <body> etc. tags included. If not, you can remove the parse_body function above. If yes, we need to clean them up. (This would also be an issue with the JavaScript approach you experimented with in the OP.)
We can accomplish this with a simple regular expression function included in the press.php file:
function parse_body($html) {
if (preg_match('#<body>(.+)</body>#is', $html, $match)) {
return trim($match[1]);
}
return 'No content matched!';
}
Then, all you'd need to do is make a link like press.php?year=2019, and have plain text page index files in the indexes folder. You could double up your index files to generate the HTML you posted in your comment to the OP, suppose a file called monthly.php, with the second half of the code above replaced with:
// Output header
make_header("Links to Monthly Press Articles for Year {$year}");
// Output links to monthly pages
foreach($texts as $file) {
echo "{$file}";
}
That would give you monthly summaries with links: Simply link to monthly.php?year=2019 (or whichever year) to get a year's links summary. Less manual HTML coding = less errors, easier updating, and more time saved for actual productive work. :)
Now, there are fancier ways of doing this. This would be the first step in leveling up from manual HTML writing. With a bit of experimentation and a couple of basic PHP tutorials, you could easily customize this and adapt it to different contexts.
This isn't an answer to tweaking the JavaScript in the OP to do the job; but it is a fairly simple solution to the actual question, "I am trying to include many HTML files into a specific DIV". This answer turned out to be "code writing service", which SO by definition is not. But you're on with a good cause, so. Best of luck, hope this helps.

loaded js works different to hardcoded

I have the following script that works perfect.
<script type="text/javascript">
$(document).ready(function() {
php_test();
});
</script>
<script type="text/javascript">
function php_test() {
alert('<?php echo(DIR); ?>myfile');
}
</script>
The output is as expected:
http://localhost/mvc_framework/myfile
when I put the function php_test in a file lets say ‘php_test.js’ and bind it to my footer it executes with this output:
<?php echo(DIR); ?>myfile
Any explanation? Im confused…
The way you asked the question makes it confusing. It is possible to make PHP run on all types of files on your server with a bit of Apache tweaking. My solution will make your JS files be processed by the PHP interpreter.
What you need to do is create a .htaccess file if you are using Apache. I am going to assume you are. Then you add this line into it:
AddType application/x-httpd-php .php .js
The above code will force the PHP interpreter to run on all the formats listed in the command. You can also add .htm or even .css if you need PHP to do something with those files on the server side.
Refer to this question here for a previous solution to similar question > Using .htaccess to make all .html pages to run as .php files?
Or you can just store a whole bunch of variables from the PHP end on the page as Javascript variables like this example from one of my projects:
<script type="text/javascript">
var trackFilterFlag = null;
<?php
echo "trackFilterFlag = \"". $displayedPageType ."\";\r\n";
?>
var trackFilterCategory = null;
<?php
if(strcmp($displayedPageType, "mood") === 0 || strcmp($displayedPageType, "genre") === 0) {
echo "trackFilterCategory = \"". $filterCategory ."\";\r\n";
}
?>
var sortingTracksBy = null;
<?php
if( isset($chosenSortFlag) && strlen($chosenSortFlag) > 3 && !($defaultSort) ) {
echo "sortingTracksBy = \"". $chosenSortFlag ."\";\r\n";
}
?>
</script>
Of course I was still a novice when I wrote that code, it's possible to make it much neater and just make PHP echo the whole thing, but you understand what I mean :)

PHP var->Javascript->PHP

I'm working on a project that has the following problem:
The database gives(via php) an array with a list of JavaScript files that need to be loaded. it is stored in the variable $array(php). I need to extract those source files with php(foreach loop) and load them via JavaScript. It is like this:
document.write("<?php foreach($js_files as $filename) {if( trim($filename) <> "" ){echo '<script type=\'text/javascript\' src=$filename></script> \n';}} ?> ");
The problem is that it loads a couple of files but goes wrong with the first one(a google api file). Does anyone have a sollution to this? Or any ideas in which direction i have to look.
This is a bad idea on multiple levels, but can be fairly easily resolved. But first:
1) Never use document.write(). To dynamically load a script it is better to use:
var script = document.createElement('script'); //create a script element
script.src = 'javascript.js'; //path to src file
//now get the body element and append the new script element
document.getElementsByTagName('body')[0].appendChild(script);
2) Loading scripts like this will likely not work if they need to be loaded in a particular order, as the downloading of dynamic scripts occurs asynchronously (non-deterministic)
3) Generally speaking, you should concatenate your js files to reduce http requests, you can use a tool like grunt to make an automatic build process.
4) If you really, really want those scripts to be dynamically loaded though, you can use the process I outlined in (1) to get the file names use ajax:
//depends on jQuery, but could be written vanilla if needed
$.get('myPhp.php', function(resp){
var arr = resp.split(','); //splits returned string on the comma
var i = arr.length;
//iterate through the results set
while (i--) {
//do process from (1) above
}
});
Note that this will still have the unordered problem. If you need sequential dynamic loading check out something like require.js
If the code needs to be fired from a JavaScript function then you can get rid of the document.write, in favor of creating new script objects, and appending to the head tag.
<?php
foreach($js_files as $filename){
if(trim($filename) != ''){
echo 'var s = document.createElement("script");';
echo 's.type = "text/javascript";';
echo 's.src = "' . $filename . '";';
echo 'document.getElementsByTagName("head")[0].appendChild(s);'
}
}
?>
You have to escape the code "" in if( trim($filename) <> "" ) because the " breaks the javascript string.

Dynamically creating and loading JS

I am working on a PHP project which writes js files and executes them on page load.
Is it a good practice to write JS file dynamically and append the script tag to the page html and execute it only every page request?
Here is my working creating and linking the JS File:
<?php
if (!function_exists('setScript')) {
function setScript($script = null)
{
static $_script = array();
if ($script == null) {
return $_script;
$_script = array();
} else {
$_script[] = $script;
}
}
}
if (!function_exists('linkJs')) {
function linkJs($controllerName, $actionName)
{
$jsFileName = randomString(40) . '.js';
$folderName = PUBLIC_DIR . DS . 'generated';
if (!is_dir($folderName)) {
mkdir($folderName);
chmod($folderName, 777);
}
$fileName = $folderName . DS . $jsFileName;
$availableFiles = scandir($folderName);
unset($availableFiles[0]);
unset($availableFiles[1]);
foreach ($availableFiles as $file) {
$file = $folderName . DS . $file;
if (is_file($file)) unlink($file);
}
$script = "$(document).ready(function() {\n" . implode("\n", setScript()) . "});";
file_put_contents($fileName, $script);
$url = loadClass('Url', 'helpers');
return "<script type='text/javascript' src='" . $url->baseUrl() . 'public/generated/' . $jsFileName . "'></script>";
}
}
if (!function_exists('alert')) {
function alert($message, $returnScript = false)
{
if (isAjax()) {
if ($returnScript) {
return "\nalert('$message');\n";
}
echo "\nalert('$message');\n";
} else {
setScript("\nalert('$message');\n");
}
}
}
Please suggest if this is a good practice in doing so or any other way i can do it.
Approx 30-40 users would be logged in to the website concurrently and would have approx 5-10 page requests per second. (These are projections. Might go high).
is writing js file (to the hard drive) and linking it is a good practice or just adding the raw scripts to the html body is a good practice since writing to js file gets the js to be un-intrusive.
Also, the javascript generated is going to be dynamic, probably for every page request.
If you can see no other choice than dynamically generating every time (my guess is that the content of the script is at least 80% different for each request) then write the script directly into the html file as linking will cause the browser to make another request to include the script.
You are already going to have degraded performance by dynamically generating the file.
The best way of doing this that I can think of is to actually create a php script that generates the js by itself and then create a .htaccess rewrite rule to rewrite /script/generator/{HASH_FOR_REQUEST}.js to /path/to/php-script-generator.php so that you can leverage browser caching if the request is the same.
However, if it is only specific details about the JS that change and the js functions body remains pretty similar (ie, you are using the js to report info back to the client) then consider writing the js in a php file and then using php inline tags to echo the stuff you need to change.
For example:
This script will write an alert to the js so then when loaded with a query string it will report back what is in the query...
<?php
// disable output buffering
/* the reason for this is that the browser will wait
* for the first byte returned before continuing with the page.
* If it has to wait for the whole file performance will be degarded.
*/
while(ob_get_level() != 0) ob_end_clean();
header("Content-type:text/javascript");
// it is wise to set some cache headers here
if(isset($_GET['message']) {
$message = urldecode($_GET['message']);
} else {
$message = "No message!";
}
?>
// write the js...
alert("<?php echo $message; ?>");
By requesting /path/to/script.php?message=hello+world the script will return alert("hello world");

fwrite php, file is not really saved?

I have a javascript file called in my webpage. It contains only one var :
var tab = [ "img1.jpg" ,
"img2.jpg" ,
.......... ,
"img100.jpg"
]
"img_i_.jpg" in tab are from my data base.
I've written a php code to update this file.
...
$res = mysql_query($sql) or die(mysql_error());
$script="var tab= [\n";
while($r = mysql_fetch_assoc($res) )
$script .= "\t\"" . $r['name']"\",\n";
$script = $script."];\n";
$fileName = fopen("js/tab.js", "w");
fwrite($fileName, $script);
fclose($fileName);
...
When I check out my js file, all is correctly written, but when I reload my page, nothing has changed.
Curiously, when I edit that js file manually, and then save it then my webpage changes after reload.
Why ? And how to solve it ? Thanks
You might be writing your file in a different location. Check the current directory under which the php page is run, and try to specify an absolute path to fopen rather than a relative one.
dirname(realpath(__FILE__)) will return the path to the folder where the current php file is stored, so you can generate absolute paths through that.
Edit: I'd also suggest doing some error checking around fopen, so that you know if the file was really opened.
Extra
You should really change your mysql_* calls to at least mysqli_* or PDO. The original mysql extension is old, doesn't support prepared statements and has been deprecated (and is due for removal).

Categories