I want to make my photo captions editable and then save the changes in localstorage. It works for the first photo but when I want to edit another, changes are saved to this first photo and not the one I edited.
Here's part of my code where I display photos with captions:
<div class="gallery">
<a href="<?=$path1; ?>">
<img src="<?= $path1; ?>">
</a>
<div id="contenteditable">
<p id="caption-photo" contenteditable> <?=pathinfo($path1, PATHINFO_FILENAME)?></p>
</div>
</div>
And it is my js code to save the changes:
const editables = document.querySelectorAll("[contenteditable]");
editables.forEach(el => {
el.addEventListener("blur", () => {
localStorage.setItem("dataStorage-" + el.id, el.innerHTML);
})
});
for (var key in localStorage) {
if (key.includes("dataStorage-")) {
const id = key.replace("dataStorage-","");
document.querySelector("#" + id).innerHTML = localStorage.getItem(key);
}
}
Okay lemme open your mind a bit ... also pardon me for the many answers, I just like comprehensive answers:
Create a new php file with the name update_file.php and put it within the same directory. Then put the php code that handles the requests in this file.
Why is this important? Because we are depending on the responseText being received from the php file which will tell us whether the request was successful or not. And, when the php that handles the request is within the same file as the html, the request will return a response containing the html content of the page --- You can experiment this yourself and see that if you put the code below within the same file, the responseText will be the whole code in the page, and that's not what we want, we want either 0 or 1 ... ok, enough said:
Put this in update_file.php in the same directory as the current file:
<?php
if(isset($_GET["old_name"]) && isset($_GET["new_name"]) && isset($_GET["directory"]) && isset($_GET["extension"])){
$old_name = $_GET["old_name"];
$new_name = $_GET["new_name"];
// The new values from the GET request
$directory = $_GET["directory"];
$extension = $_GET["extension"];
// echo $directory;
// echo $extension;
// Concatenate the values with the directories
// 1 thing to note, if the image is in the current directory,
// the value you will receive for $directory will be "."
// So the method below ensures flexibility with different directories
$dot = ".";
// $dot is added before the extension
$slash = "/";
// $slash is added after the directory name
// if ".", it will be "./' -- for current directory
// if "some/directory" , it will be "some/directory/"
// Then add to the file name and the extension
$full_oldname = $directory . $slash . $old_name . $dot . $extension;
$full_newname = $directory . $slash . $new_name . $dot . $extension;
echo rename($full_oldname, $full_newname);
}
?>
Then this is your current file:
<?php
$some_records = ["record1.jpeg", "uploads/record2.jpeg", "images/subdirectory1/record3.jpeg", "images/record4.jpg", "images/subdirectory2/record5.jpg"];
// Assuming your directory has subdirectories
$counter = 1;
?>
<div class="gallery">
<?php foreach ($some_records as $path) {
echo '<a href="' . $path . '">
<img src="' . $path . '">
</a>
<div id="contenteditable">
<p id="caption-photo' . $counter . '" contenteditable>' . pathinfo($path, PATHINFO_FILENAME) . '</p>
<input type="hidden" name="directory-"' . $counter . '" value="' . pathinfo($path, PATHINFO_DIRNAME) . '" />
<input type="hidden" name="extension-"' . $counter . '" value="' . pathinfo($path, PATHINFO_EXTENSION) . '" />
</div>';
// Note the 2 hidden inputs above
$counter++;
}
?>
</div>
<script>
function update_file(old_name, new_name, directory, extension) {
// The function has been updated with the new parameters
var update = new XMLHttpRequest();
update.open("GET", "update_file.php?old_name=" + old_name + "&new_name=" + new_name + "&directory=" + directory + "&extension=" + extension, true);
// The XHR request has also been updated with the new values
update.onreadystatechange = function() {
if (this.readyState == this.DONE && this.status == 200) {
if (this.responseText != null) {
console.log(this.responseText);
// This will either be 0 or 1, if correct values have been passed to it
if(this.responseText == 1){
console.log("Renamed successfully!");
}
else {
console.log("Error renaming!");
}
}
else {
console.log("Not sent!!");
}
}
};
update.send();
}
document.addEventListener("DOMContentLoaded", function(){
const editables = document.querySelectorAll("[contenteditable]");
editables.forEach(el => {
var curr = el.innerHTML;
// The next element after "el" is the first hidden input with the directory
var dir = el.nextElementSibling.value;
// The next element after the above hidden input is the second hidden input with the extension
// Note the 2 ".nextElementSibling" accessors
var ext = el.nextElementSibling.nextElementSibling.value;
// To get the value of any input(that can lie within a form control) use "[element].value'
console.log(ext);
console.log(dir);
el.addEventListener("blur", () => {
localStorage.setItem("dataStorage-" + el.id, el.innerHTML);
console.log(el.innerHTML);
update_file(curr, el.innerHTML, dir, ext);
})
});
for(var i = 1; i < editables.length+1; i++){
console.log("dataStorage-caption-photo" + i + " => " + localStorage.getItem("dataStorage-caption-photo" + i));
}
});
</script>
Also read the comments, the main points here are:
How to add the hidden input elements with the respective values
How to access the values with javascript
How to add them to the XHR request and then capture them with php
Finally, how to concatenate them and get your full path
Hope this helps
Here is some developer tools you can be using, I'm not sure which browser you are using but you might find such a similar thing, go to the console tab then click on settings and enable logging of XMLHttpRequests
You will be able to see the requests right after you remove focus on any contenteditable element and confirm whether they are being sent
Here's a suggestion: suppose your foreach loop is:
<?=
#Other php stuff here
#You can define a counter variable:
$counter = 1;
?>
<div class="gallery">
<?= foreach($some_records as $your_value){ ?>
<a href="<?=$path1; ?>">
<img src="<?= $path1; ?>">
</a>
<div id="contenteditable">
#Which you can append to the caption-photo
#So the id of the first will be: caption-photo1
<p id="caption-photo<?= $counter ?>" contenteditable> <?=pathinfo($path1, PATHINFO_FILENAME)?></p>
<?=
$counter++;
#At the end of each loop, increase the value of counter by 1
}
?>
</div>
Also don't mind the foreach loop, I'm sure it doesn't match yours, but just get the aspect of appending a number to the id so that you can get different values
Okay since that doesn't work, here is a snippet of the above but without using the short_open_tags(<?= ... =>), Instead I just used the php(<?php ... ?>) tags as they are:
Try running the code as it is first and check the logs
<?php
$some_records = ["record1.jpg", "record2.jpg", "record3.jpg", "record4.jpg", "record5.jpg"];
$counter = 1;
?>
<div class="gallery">
<?php foreach ($some_records as $path) {
echo '<a href="' . $path . '">
<img src="' . $path . '">
</a>
<div id="contenteditable">
<p id="caption-photo' . $counter . '" contenteditable>' . pathinfo($path, PATHINFO_FILENAME) . '</p>
</div>';
$counter++;
}
?>
</div>
<script>
document.addEventListener("DOMContentLoaded", function(){
const editables = document.querySelectorAll("[contenteditable]");
editables.forEach(el => {
el.addEventListener("blur", () => {
localStorage.setItem("dataStorage-" + el.id, el.innerHTML);
console.log(el.innerHTML);
//When you change the value, it is logged
})
});
/* The loop below does not work as expected */
// for (var key in localStorage) {
// if (key.includes("dataStorage-")) {
// const id = key.replace("dataStorage-", "");
// document.querySelector("#" + id).innerHTML = localStorage.getItem(key);
// ---- The above direct way of selecting the element does not work
// console.log(localStorage.getItem(key));
// }
// }
/* 1 is added to editables.length because the counter starts
from 1 and not 0 */
for(var i = 1; i < editables.length+1; i++){
console.log("dataStorage-caption-photo" + i + " => " + localStorage.getItem("dataStorage-caption-photo" + i));
//This logs all the values associated with the elements
}
});
</script>
This is how the elements are set in the above code:
As you can see the counter is working ok.
And based on your loop that is commented out, this part returns an error because that "direct" method of accessing elements does not work:
Here is some code to assist you:
Place this one before everything in your php file
if(isset($_GET["old_name"]) && isset($_GET["new_name"])){
$old_name = $_GET["old_name"];
// The same variables in the `GET` request
$new_name = $_GET["new_name"];
// Also remember the extension of the files
$ext = ".jpeg";
// As for rename you have to give the full path
// If your folder is uploads/, and the file is oldname.jpg
// Then it should be rename("uploads/" . $old_name $ext, "uploads/" . $new_name . $ext);
// Just provide the full path to the file you are renaming
// If the images are within the same directory, its ok as it is
echo rename($old_name . $ext, $new_name . $ext);
// returns true if successful
// returns false if not successful
// This is the "responseText" that Javascript will be logging
}
And add this function at the very beginning of your <script> tags:
function update_file(old_name, new_name) {
var update = new XMLHttpRequest();
// Initialize the request
update.open("GET", "?old_name=" + old_name + "&new_name=" + new_name, true);
// Put the variables in the request which will be captured by php
update.onreadystatechange = function() {
if (this.readyState == this.DONE && this.status == 200) {
if (this.responseText != null) {
if(this.responseText){
console.log("Renamed successfully!");
}
else {
console.log("Error renaming!");
}
}
else {
console.log("Not sent!!");
}
}
};
update.send();
}
Then change this section of the code to this:
const editables = document.querySelectorAll("[contenteditable]");
editables.forEach(el => {
var curr = el.innerHTML;
// Get the current value before it changes
el.addEventListener("blur", () => {
localStorage.setItem("dataStorage-" + el.id, el.innerHTML);
console.log(el.innerHTML);
update_file(curr, el.innerHTML);
// Call the XMLHttpRequest with the values
})
});
This should give you a head start on how to use XHR requests (that's if you don't use them) ... This is only because for you to get data from javascript to php it has to be through GET or POST ... but data from php to javascript is as easy as putting php tags with the value inside of it.
Also there are literally comments everywhere so you can read and understand how and why it works. Don't hesitate to ask for help.
----------
Ok, as you work on that, here's a tip -- within the foreach loop, you can echo a hidden input as so: ... <input type="hidden" name="directory-' . $counter . ' " value=" ' . pathinfo($path1, PATHINFO_DIRNAME) . ' "/> (assuming this code is inside the foreach loop) ... and also a same hidden input below it for the extension, since images may have different extensions --(PATHINFO_EXTENSION) then instead of "directory-(number)", you have "extension-(number)" ... then update the request to send also the extension and the directory -- [update_info(old_name, new_name, extension, directory)] ... meaning you also update the XHR request to send those too ... And on the php side, you just concatenate the directory with the file name and the extension received.
Now when it comes to actually getting the values from the hidden inputs, remember there is a counter, so based on the value of el.id, which ends with a specific number, you take the value of the hidden input which has a name ending with the same number (this is within the forEach loop) for example for the value of extension, take value whose name attribute starts with "extension-" and ends with the same value as the one for el.id ... do this as well for the directory
Another option is to take the el.nextElementSibling.value for the first hidden input and then the next one too, and those will be the values for directory and extension...
I can actually write all of them down in code but it won't be a learning process for you, happy coding :) ... Hope you can understand the concept in the above explanations
Related
I have been trying to export a search result to an Excel file (type .xls), before this, I have been using purely PHP and it works.
However, my client requests to have "live search" effect, so I have to shift to AJAX.
Here is the starting point: User clicks "Export" button, and in the javascript (in the main php file viewdata.php):
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
....
$(document).ready(function () {
var guid = <?php echo $guid ?>;
var date = document.getElementById("cbXDate").value;
var key = document.getElementById("cbsearch").value;
console.log("GUID: '" + guid + "', Date: '" + date + "' Key: '" + key + "'");
$.post("export_contacts.php",
{ sGuid: guid, sDate: date, sKey: key },
function () { console.log("Complete"); } );
});
cbXDate is an input field of type date to let user choose a date from whence to export the data, and cbsearch is a text input field to include a search keyword. console commands are added to see where the code execution has went through.
in the export_contact.php:
<?php
echo '<script> console.log("Export PHP activated."); </script>';
?>
I removed the PHP MySQL data selection code just to debug the problem (full source code below).
Problem is: export_contacts.php is never called. The "Export PHP activated" message never popped up in the console. The console only displayed the data values and "Completed", i.e. export_contacts.php was never called.
Output:
GUID: '0001', Date: '2021-08-01' Key: 'Jo'
Complete
Out of curiosity, I replaced $.post(...) with $("#export_div").load(...) and the console message showed up:
$(document).ready(function () {
var guid = <?php echo $guid ?>;
var date = document.getElementById("cbXDate").value;
var key = document.getElementById("cbsearch").value;
console.log("GUID: '" + guid + "', Date: '" + date + "' Key: '" + key + "'");
$("#export_div").load("export_contacts.php",
{ sGuid: guid, sDate: date, sKey: key },
function () { console.log("Complete"); } );
});
Output:
GUID: '0001', Date: '2021-08-01' Key: 'Jo'
Export PHP activated.
Complete
But this is not what I want, I want to write the output to a file, not display them in a div in the webpage. However, the data shown in the "export_div" div is correct, but the header part is not running, I know the quirkyness in header() calls, but I didn't output anything before the header() calls (unless output from the calling viewdata.php file also count?), here is the full export_contacts.php source code:
<?php
include("./php/auth.php");
$guid = $_POST['sGuid'];
$date = $_POST['sDate'];
$skey = $_POST['sKey'];
$searchKey = $_POST['sKey'];
if($searchKey == "")
{
$skey = "'%'";
}
else
{
$skey = "'%".$searchKey."%'";
}
$sql = "SELECT *, FROM_UNIXTIME(ROUND((date / 1000), 0) + 46800) AS date
FROM contacts
WHERE owner = '$guid' AND contact <> ''
AND (contact LIKE $skey OR name LIKE $skey) ";
if(!empty($date))
{
"AND date >= '$date' ";
}
$sql .= "ORDER BY contact;";
if($result = mysqli_query($link, $sql))
{
$columnHeader = '';
$columnHeader = "Owner" . "\t" . "Contact" . "\t" . "Name" . "\t" . "SaveDate" . "\t";
$setData = '';
while($rows = mysqli_fetch_assoc($result))
{
$rowData = '';
foreach ($rows as $value)
{
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
// in case of .load() used,
// code works up until this point
// code doesn't work since here...
header("Content-type: application/xls");
header("Content-Disposition: attachment; filename=contact_".$guid.".xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
// until here
// this will show in console in case of .load() used
echo '<script> console.log("Export PHP activated."); </script>';
die();
}
else
{
echo "<script>window.alert('ERROR: '".mysqli_error($link).")</script>";
}
include("./php/cleanup.php");
?>
This code is working in the pure PHP version. I don't know why this header() part isn't working in here, could be due to its output got redirected to the div?
To make things clear, my question is: "Why $.post(...) isn't calling the PHP file, while $("#export_div").load(...) did?".
The header() part is just a sub question, and is fine if it's ignored.
As Kmoser pointed out, I was doing things wrong. None of the tutorial sites I visited did mention that $.post() will not return any result at all, while my php code is expecting the return of the search result and write them in a file in the header() calls.
I am currently working with a web-based document management system, I am creating it as a single page using ajax/php connection. I have my file tree view, that displays the folders and files using this code:
if (isset($_GET['displayFolderAndFiles'])) {
function listIt ($path) {
$items = scandir($path);
foreach ($items as $item) {
// Ignore the . and .. folders
if ($item != "." AND $item != "..") {
if (is_file($path . $item)) {
// this is the file
}
else {
// this is the directory
// do the list it again!
echo "<li><span class='fa fa-chevron-right caret'></span><button class='btn-der' id='directory" . $id . "' onclick='directoryAction(this);' value='" . $path . $item . "/'>" . $item . "</button>";
echo "<ul class='nested'>";
listIt($path . $item . "/");
//echo("<input type='text' value='".$path.$item."/'>");
echo "</ul></li>";
}
$id++;
}
}
}
listIt("./My Files/");
}
with this code it is hard for me to manipulate the tree view. I use ajax to get the result.
What I want is to reload the tree view when i add, delete file or folder. I also want to load the page once I do some queries in my application without refreshing the page.
I want to have the functionalities like the sample image, the application is FileRun.
Can someone recommend or suggest some ways to address my problem.
Will I use some javascript library or else?
Reference/Sample: Web-based Document Management System (FileRun)
You can use something like this:
public function treeArr($dir){
// First we get the directory
$paths = scandir($dir, SCANDIR_SORT_NONE);
// We remove .. && . from our array
unset($paths[array_search('.', $paths, true)]);
unset($paths[array_search('..', $paths, true)]);
// Add empty array for our tree
$arr = [];
// Check isour paths array empty
if (count($paths) < 1)
return;
// If not empty we get through all paths and add what we want
foreach($paths as $path){
$current_dir = $dir.'/'.$path;
$isDir = is_dir($current_dir);
$expandable = count( scandir( $current_dir ) ) > 2 ? true : false;
// In my case, I needed path name
// Is it expandable (as is it directory and does it contains or is it empty)
// Is it dir or file, if it is not dir it will be false so its file
// And path for that folder or file
$path_data = [
'name' => $path,
'expandable' => $expandable,
'isDir' => $isDir,
'path' => $current_dir,
];
if($expandable) $path_data['data'] = $this->treeArr($dir.'/'.$path);
// If our dir is expandable we go to read files and folders from in it and call self function with that path
array_push($arr, $path_data);
// At the end we add everything into array
}
return $arr;
}
It works for my needs and on client side you can style and add this as you like.
Within foreach you can check for other things, like file extension, date, size and pass everything you need about that. Like if it is html file and you have some live editor, you can check is it html and if it is add like 'isHTML' => true, and then on front:
if(file.isHTML) { //run the code }
I posted this earlier but it incorrectly got marked as a duplicate of Can scripts be inserted with innerHTML?, which isn't my problem. I'm not trying to run any JavaScript through using innerHTML, I'm trying to run JavaScript that is located in a PHP file called through Ajax/XmlHttp. I am using innerHTML in that JS, but I'm not writing more JS within that. So it's not a duplicate of that question and I'm trying it again now.
Not sure what's going on here. I'll explain the organization of my files first and then get into the code.
The application- Allows the user to select different attributes (i.e. year or name) and view pictures of matching results from a database.
Files- I have a gallery.php file that has a series of HTML form elements acting as selectors to get filtered results from a database. Whenever a selector is set or changed, the file sends a new request to a get.php file that uses Ajax to refresh the results without loading a new page. All that works great. My next task is to implement a modal section where I can click on an image and view a bigger version which I plan to do with JavaScript and CSS, but my intermediate goal is to just change some text at the bottom of the results from get.php again using JavaScript, just as a first step. But I can't seem to get any JavaScript written in get.php to fire.
Code-
This is gallery.php:
<?php
include_once("./../php/navbar.php");
?>
<html>
<head>
<link href="/css/siteTheme.css" rel="stylesheet">
<style>
.attributes span {
margin-right: 1rem;
}
</style>
<script>
function changeParams() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML = this.responseText;
}
};
year = document.getElementById("years_select").value;
nameFirst= document.getElementById("nameFirst_select").value;
/* Ton of other getElementById statements here that I'm excluding to keep things shorter */
url = "get.php?year="+year+......;
xmlhttp.open("GET", url, true);
xmlhttp.send();
} /* End function */
</script>
</head>
<body>
<div class="content">
<h1>Gallery</h1>
<form>Details:
<!-- -------------------- Year -------------------- -->
<select onchange="changeParams()" name="years" id="years_select">
<option value="All">Year</option>
<?php
include("/var/www/admin.php");
$conn = mysqli_connect($dbServername, $publicdbUsername, $publicdbPass, $dbName);
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
$sql = "select year from db group by year order by year desc";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo "<option value=" . $row['year'] . ">" . $row['year'] . "</option>";
}
mysqli_close($conn);
?>
</select>
<!-- A bunch of other selectors are created here following the same pattern as above of getting results from a DB -->
<!-- -------------------- Searchbar -------------------- -->
<input type="text" size="50" onkeyup="changeParams()" name="search" id="search" placeholder="Search"></input>
</form>
<div id="test">Choose some filters to see some results!</div>
</form>
</div> <!-- Ends content div -->
</body>
</html>
This is get.php:
<html>
<head>
<style>
/* Bunch of CSS that's not relevant here */
</style>
<script type="text/javascript">
console.log(".....");
var parts = document.querySelectorAll("div.imgContainer");
console.log("Found something:", parts);
parts.addEventListener("click", function(){
document.getElementById("anID").innerHTML = "Test...";
});
</script>
</head>
<body>
<?php
include("/var/www/admin.php");
$year = $_GET['year'];
//Bunch of other variables set here following the same logic, getting data from gallery.php
$conn = mysqli_connect($dbServername, $publicdbUsername, $publicdbPass, $dbName);
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
echo '$conn';
}
$sql = 'select * db';
/* ---------- Creating SQL statement ---------- */
$clauses = 0;
if ($year != "All") {
if ($clauses == 0) {
$sql = $sql . ' where year = "' . $year . '" and';
$clauses = $clauses + 1;
} else {
$sql = $sql . ' year = "' . $year . '" and';
}
} /* Bunch of other if statements to get set information and add to sql statement as such */
// Need to chop of the last ' and' from the sql statement
$sql = substr($sql, 0, -4);
$sql = $sql . ' order by year desc';
$result = mysqli_query($conn, $sql);
$num_results = mysqli_num_rows($result);
if ($num_results == 0 or $clauses == 0) {
echo "<p>No matches to your query. Try refining your search terms to get some results.</p>";
} else {
echo "<p>" . $num_results . " results matched your query.</p>";
echo "<div class=results>";
//echo "<div>";
echo '<script type="text/javascript">
function modalFunction() {
document.getElementById("anID").innerHTML = "test";
}
</script>';
while ($row = mysqli_fetch_array($result)) {
$pic = $row['pathToPic'];
$wwwImg = substr($pic, 13);
//echo "<span id=aCard><img src=" . $wwwImg . " height ='250px'>";
//echo "<span class=text>" . $row['fullCardInfo'] . "</span></span>";
echo "<div class=fullContainer><div class='imgContainer'><img class=image src=" . $wwwImg ."></div><p class=text>" . $row['fullInfo'] . "</p></div>";
} // End while of results
echo "</div>";// End results div//</div>";
//echo '<div class="modal"><p id="anID"></p></div>';
} // End else of "if results"
mysqli_close($conn);
?>
<script>
</script>
<div>
<p id="anID">This in a div</p>
</div>
<!--<span>
<p id="anID">This in a span</p>
</span>-->
</body>
</html>
Sorry if that was messy, I chopped out a bunch of stuff that just gets/selects/filters some data. All that works and all variables that are left in there are set in my full code.
But the issue I'm having is writing JavaScript in get.php to change the text in the <p id="anID"> tags. I've tried JS in a few different areas of get.php, from in the <head> tags, to echoing it in <script> tags in the PHP, to pure <script> tags after the PHP statements are done (I think I left them in a few different places).
Problem is that nothing I do works to change the text in the <p> tags I references. Additionally, the console.log statements in the header of get.php don't seem to get called either. They don't fire no matter where I place them in get.php. Console.log works fine in gallery.php so it's not some issue with my browser or anything.
Long term, I will be adding JS query selectors to bring up a bigger image when an image is clicked on, but for now I'm just trying to make ANY JavaScript work in get.php and I'm struggling to do so. I don't see how this is a duplicate of the suggested repeat as I'm not trying to run JavaScript through innerHTML here.
Scratch that, it actually is trying to pass JavaScript through innerHTML as the information from get.php comes from this section of gallery.php:
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML = this.responseText;
console.log("Response: ", this.responseText);
}
So it appears this is a duplicate of the question I linked after all. Apologies. However, there are not great answers to that question, so any tips would be appreciated.
This line:
document.getElementById("test").innerHTML = this.responseText;
Is simply going to add the contents of this.responseText to the element test. I'm sure you understand that much, but what you want to do is completely wrong. The scripts within the output of get.php will NOT be executed at all and you have corrupted your HTML as well by including a second <html><head> and more.
A better approach would be if get.php returned the data from you DB query as a JSON string like so:
$data;
while ($row = mysqli_fetch_array($result)) {
$data[]['pic'] = $row['pathToPic'];
$data[]['wwwImg'] = substr($row['pathToPic'], 13);
}
echo json_encode($data);
exit;
And then back on gallery.php you do something like:
if (this.readyState == 4 && this.status == 200) {
formatResult(this.responseText);
}
// ... snip ...
function confirmJson(str) {
var j = null;
if (str) {
try { j = JSON.parse(str); }
catch (e) { j = null; }
}
return j;
}
function formatResult(str) {
var data = confirmJson(str);
if (! data) {
console.log("result is not JSON");
return;
}
// do stuff with the data
var i, max = data.length;
var h = document.createElement("div");
var img;
for(i=0;i<max;i++) {
img = document.createElement("src");
img.src = data[i].wwwImg;
img.addEventListener("click",function(){ alert("pic:["+ data[i].pic +"]"); },true);
h.appendChild(img);
}
document.getElementById("test").innerHTML = h;
}
I've got a html file, in which I am dynamically loading data using AJAX and PHP.
They are no big deal, as they work fine, but I still have got a Problem.
I have (for showing purposes) created two divs, which are showing literally the same in DOM, but one is also shown in the source code. (The one div is loaded dynamically, in the other one I've loaded the results already from the start.)
Like this:
<div>
<ul>
<!-- Here is some data which is shown correct -- >
<!-- (too much to REALLY put it in here -->
</ul>
</div>
<div id="result">
<!-- This should show the exact same output, but well isn't... -->
</div>
I've already looked after some similar things, but nothing helped me solve my Problem, as my request for the "result" is
function kommissionsakte(o, s) {
$("#result").empty();
var xmlHttp = {};
xmlHttp = ajaxHandler(xmlHttp);
// Wenn das Objekt erfolgreich erzeugt wurde
var url = "ajax/getKommissionsakten.php";
suchwert = escape($("#suchwert").val());
var params = "o=" + o + "&s=" + s + "&suchwert=" + suchwert;
if (suchwert != '') {
$("#suchwert").css("border-color", "#31ae1c");
loading();
xmlHttp.open("POST", url, true);
//Headerinformationen für den POST Request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
$("#result").html(xmlHttp.responseText);
closeLoading();
}
};
xmlHttp.send(params);
} else {
$("#suchwert").focus();
$("#suchwert").css("border-color", "#b20e10");
}
}
My idea was to somehow get #result not as div id but INTO the div, but I am bad, so I have no idea how.
EDIT: Okay Long Explanation:
I try to load a Filetree using jquery into a page, that is already loaded. The Code creating the tree is working fine, it just doesn't work when I try to load it into this page. I've read that jquery is using DOM and not source code, so it should work properly, but it doesn't.
I can search for a keyword in a search function and the file tree is showing them. In the manually created div, is the Code, which creates the tree and jquery is manipulating it properly, if I now load that exact same Code into the other div, jquery isn't manipulating it.
Also i Am REALLY (like REALLY REALLY bad at JS) so it would be very, very nice to have a long Explanation in the answer.
EDIT2:
Requested PHP File Code:
<?php
include '../include/ebene.inc.php';
include $ebene.'include/error_reporting.inc.php';
include $ebene.'include/db.inc.php';
include $ebene.'include/getSprache.inc.php';
include $ebene.'include/funktionen-standard.inc.php';
include $ebene.'include/funktionen-individuell.inc.php';
include $ebene.'include/konfig.inc.php';
if(isset($_POST['suchwert'])){
$suchwert =($_POST['suchwert']);
$php_file_tree = '';
$first_call = true;
$neue_seite = false;
if($suchwert != ''){
$parentsql = "SELECT TOP 10 KOM_Nummer from dbo.V_Kommisions_Akte_EN WHERE KOM_Nummer LIKE '%$suchwert%' group by KOM_Nummer";
$parameter = array();
$optionen = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$parent = sqlsrv_query($dbD3, $parentsql, $parameter, $optionen);
$parentanzahl = sqlsrv_num_rows($parent);
if($parentanzahl != 0){
$neue_seite = true;
if($anzahl >= 200){
echo '<br /><div align="center">'.$var['verfeinern'].'</div>';
}else{
echo '<br /><div align="center">'.$var['anzahl_ergebnisse'].': '.$parentanzahl.'</div>';
}
$php_file_tree .= "<ul";
if($first_call) {$php_file_tree .= " class=\"php-file-tree\""; $first_call = false;}
$php_file_tree .= ">";
while($komnr = sqlsrv_fetch_array($parent, SQLSRV_FETCH_ASSOC)) {
$php_file_tree .= "<li class=\"pft-directory\">" . htmlspecialchars($komnr['KOM_Nummer']) . "<ul>";
$komnrregister = $komnr['KOM_Nummer'];
$subsql = "SELECT TOP 10 KOM_Nummer, Register from dbo.V_Kommisions_Akte_EN where KOM_Nummer = '$komnrregister' group by KOM_Nummer, Register";
$parameter = array();
$optionen = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$sub = sqlsrv_query($dbD3, $subsql, $parameter, $optionen);
$subanzahl = sqlsrv_num_rows($sub);
while($register = sqlsrv_fetch_array($sub, SQLSRV_FETCH_ASSOC)) {
$php_file_tree .= "<li class=\"pft-directory\">" . htmlspecialchars($register['Register']) . "<ul>";
$registerdokuid = $register['Register'];
$slavesql = "SELECT TOP 10 KOM_Nummer, Register, doku_id from dbo.V_Kommisions_Akte_EN where Register = '$registerdokuid' AND KOM_Nummer = '$komnrregister' group by KOM_Nummer, Register, doku_id";
$parameter = array();
$optionen = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$slave = sqlsrv_query($dbD3, $slavesql, $parameter, $optionen);
$slaveanzahl = sqlsrv_num_rows($slave);
while($doku = sqlsrv_fetch_array($slave, SQLSRV_FETCH_ASSOC)) {
$php_file_tree .= "<li class=\"pft-file ext-xls\">" . htmlspecialchars($doku['doku_id']) . "</li>";
}
$php_file_tree .= '</ul></li>';
}
$php_file_tree .= '</ul>';
}
$php_file_tree .= '</ul>';
}
echo $php_file_tree;
//return ($php_file_tree);
}
}
?>
My answer needs some edits, but you should try something like this :
function getMyPage(pageUrl,someData,callback){
$.ajax({
type : 'POST',
url : pageUrl,
data : {'postName':someData},
error : function(response){
console.log("something wrong "+response+" - "+response.responseText+" - "+JSON.stringify(response));
},
success : function(response){
callback(response);
}
});
})
Then somewhere in your code :
$("body").on("click","#yourButton",getMyPage('http://anything','your data',function(back){
$("#yourDiv").html(back);
});
If possible to run again a php line after update a table in the database?
I have html button that fire a jQuery.post:
btn.onclick = function(e) {
$.post('inc/pstPts.php',
{
pts: pts
});
}
In pstPts.php I make the query and it update the target row with success.
I had loaded that row in a html with this:
<?php
for ($i=0; $i < $q->query_numrows(); $i++) {
print '<tr><td>' . $d[$i]['user_nom'] . ' ';
print '<tr><td>' . $d[$i]['user_ape'] . ' ';
print '<tr><td>' . $d[$i]['user_email'] . ' ';
print '<tr><td>' . $d[$i]['user_cel'] . ' '; }
?>
But this had loaded the old data.
I want to run just this 5 lines after the update.
since you have very less code, i will just post pseudocode to give an idea.
Server SIde:
//get the inputs from $_POST
// update the database
$update = $db->update($_POST); //simplified. just an example
if($update !== false)
{
$entry = $db->query("SELECT * FROM foo ...... WHERE id = $_POST['id']"); //take care of sql injections.
foreach($entry as $i)
{
//build up the html and echo it
}
}
Note: to bind the params (to make the query safe from sql injection), follow the examples in this binding links
Client Side:
$.post({
//url
}).done(function(data){
$('#selector').html(data);
});
done....