sledgewhack sledgewhack - 3 months ago 8
HTML Question

How to call a PHP file in a JavaScript function

I have a small 'load.php' file which essentially cycles through the images stored on my Pi server, and simply responds with all of the png images.
However, I don't actually know what the correct way to call this file would be in JavaScript, or how to append the results to an HTML element.

load.php:

<?php
$dirname = "/var/www/html/";
$images = glob($dirname."*.png");
foreach($images as $image) {
echo '<img src="'.$image.'" /><br />';
}
?>


I tied to simply post the results and append them to a Div but that doesn't work:

$.post("load.php", function(data) {
console.log(data);
imgsDiv.innerHTML = imgsDiv.innerHTML + data;
});


Any help would be much appreciated :)

Answer

You don't have to send a post to server because you are not sending anything. Try to change your JavaScript code to use get:

$.get("load.php", function(data) {
    console.log(data);
    //And you can use jQuery to add data to a element.
    $("#imgsDiv").html(data)
});

For this you need to have a html element like this:

<div id="imgsDiv"></div>