Display file info? - php

Thanks to my previous posts, some of yall helped me setting this piece of code right there. :). It lists files in the current folder.
<?php
foreach (glob("*") as $filename) {
echo "<th class=\"icon\"><img src=\"/Home/.res/save.png\"></th><th>{$filename}<th class=\"desc\"><img src=\"/Home/.res/info.png\"></th></tr>";
}
?>
I now want to add an "info" button at the end of every file name. I succeeded. :)
Only thing is, its only able to display static text- I want that info tab to display information about the selected file. I then did some research on AJAX.
I came up with this code:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("info").innerHTML = this.responseText;
}
};
xhttp.open("GET", ".info.php", true);
xhttp.send();
This code successfully loads dynamically a page called ".info.php".
Heres the tricky part: How can I make AJAX transfer a variable (the file name) to .info.php - so that info.php can display information about the selected file?
=======EDIT: Came up with this AJAX code:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("info").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/Home/.info.php?filename=<?php echo "{$filename}" ?>", true);
xhttp.send();
}
Im now able to pass variables! (Thanks Jeff)
Sadly, the passed variable is always setted as the last file in the list, instead of being setted by the selected file. Any tips?
=========EDIT #2===========
My code right now:
First is PHP
<?php
foreach (glob("*") as $filename) {
echo "<th class=\"icon\"><img src=\"/Home/.res/save.png\"></th><th>{$filename}<th class=\"desc\"><img src=\"/Home/.res/info.png\"> </th></tr>";
}
?>
Now for the AJAX:
function loadDoc(filename) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("info").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/Home/.info.php?filename=" + filename, true);
xhttp.send();
}
Cheers.

You need to pass the specific filename as a parameter to your PHP page.
The issue with your first update is that foreach iterates over the array assigning the value to the "temporary" variable.
foreach (glob("*") as $filename) {
After the iteration is complete that variable ($filename, which should be considered temporary) contains only the last value of that array. So your JS function just has a statically defined file name.
The JS call should pass in the filename, and the JS function should take in a value and use it when making the call.
PHP:
onclick=\"loadDoc('{$filename}')\"
JS:
function loadDoc(filename) {
....
xhttp.open("GET", "/Home/.info.php?filename=" + filename, true);

Related

Unable to execute PHP code from extenal file with GET request

While learning JQuery and AJAX, I came across some exercises with GET requests to external files. (https://www.w3schools.com/xml/ajax_php.asp)
My JQuery script is as follows:
function displaySuggestions(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("suggestions").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText)
document.getElementById("suggestions").innerHTML = this.responseText;
}
}
xhttp.open("GET", "gethint.php?q="+str, true);
xhttp.send();
}
Code is executed with following HTML code:
<div>
<h2>Display sugestions while typing</h2>
<div>
<form>
Fill in employee: <input onkeyup="displaySuggestions(this.value)">
</form>
Suggestions: <span id="suggestions"></span>
</div>
</div>
The output of the alert function is the whole PHP file as text.
Not sure if I am doing something wrong with the PHP file itself as I get the same result with an exact copy of the example code from the link above. I have created a file "gethint.php" with an exact copy of the PHP example code displayed at the bottom of the page from the link above

Script html php

In the script below, I currently have a fixed value in the array of $out variable. Example: $out[1]. What I need is for this fixed value (in this case 1), to be replaced by the str value of the function.
str is javascript
$out[1] is php
Someone can help me?
<script>
function teste2(str) {
var xhttp;
if (str == "") {
document.getElementById("cli").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("resimg").innerHTML =
"<img src=" + "<?php echo ("img/base/".$out[1]);?>" + ">"
}
};
xhttp.open("GET", "clique.php?q="+str, true);
xhttp.send();
}
</script>
As mentioned, it doesn't make sense why you are mixing PHP in your JS. If you need data from the server side usable by your client side JS, there are multiple approaches.
The preferred approach is to make an API endpoint you can call and return JSON.
Another approach (not recommended) is to output a JSON object in a script tag on server render and then access it like:
<script>
let data = <?php echo(json_encode($myData)); ?>;
</script>
To answer your question though, you can set the value with JS since the variable you want is client side:
function teste2(str) {
var xhttp;
if (str == "") {
document.getElementById("cli").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let src = 'img/base/' + str;
document.getElementById("resimg").innerHTML = '<img src="' + src + '">';
}
};
xhttp.open("GET", "clique.php?q="+str, true);
xhttp.send();
}
Well, PHP scripts run on the server side, while Javascript ones run on the client's browser.
Therefore, the value of str will only be resolved at runtime, when the function is called on the user's browser. There is no way for your PHP script to know in advance what the value will be, as your PHP script runs before any JS does.
I am sorry, but I believe you should re-imagine your design here.
Edit: I assume your $out is a PHP variable, right?

How to go back to a function in jquery

I have some buttons when a user click one of them they update the content of the page through ajax then the buttons are hidden and some new buttons are available for user. The problem is when i hit the back button it doesn't go back to the previous function. I want the user to go back to the previous set of buttons here is my code :
$(".buttonset1").click(function() {
$('#div1').css("display","none");
id = $(this).attr("value");
query = 'ajax.php?id='+id;
myQuery(query);
$('#div2').css("display","block");
});
$(".buttonset2").click(function() {
$('#div2').css("display","none");
value = $(this).attr("value");
query = 'ajax.php?id='+id+'&var1='value;
myQuery(query);
$('#div3').css("display","block");
});
Now div2 is shown to the user.... myQuery function does the ajax query
function myQuery(url) {
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("sql").innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open('GET', url, true);
xmlHttp.send();
}
Solved it was pretty simple
History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
var State = History.getState(); // Note: We are using History.getState() instead of event.state
var url = State.url;
myQuery(url);
});

How to use file_get_contents on loop?

I'm trying to use file_get_contents on loop, in order to fetch JSON string from an URL continuously (every second). And i need to store the result into a javascript variable.
Here was my approach, but i didn't get any result from this. My page showed me nothing but endless loading.
<?php
set_time_limit(0);
while(true)
{
$jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php');
echo $jsonContent;
sleep(10);
}
?>
And here my javascript code.
setInterval(function(){
var jsonUpdPostData = <?php echo $jsonContent; ?>;
}, 100);
What should i do to make it work? Any suggestion will be appreciated.
You can make it work this way:
getContent.php
<?php
echo file_get_contents('http://megarkarsa.com/gpsjson.php');
xxxx.js
setInterval(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText); // this contains the new file contents
}
}
xmlhttp.open('GET', 'getContent.php');
xmlhttp.send();
}, 100);

script within a php page not executed when called using ajax

Please read below my scenario…
I have a PHP file wherein I have javascript within it..
<?php
echo ‘<script>’;
echo ‘window.alert(“hi”)’;
echo ‘</script>’;
?>
On execution of this file directly, the content inside the script is executed as expected. But if this same page is being called via ajax from another page, the script part is NOT executed.
Can you please let me know the possible reasons.
(note: I’m in a compulsion to have script within php page).
When you do an AJAX call you just grab the content from that page. JavaScript treats it as a string (not code). You would have to add the content from the page to your DOM in your AJAX callback.
$.get('/alertscript.php', {}, function(results){
$("html").append(results);
});
Make sure you change the code to fit your needs. I'm supposing you use jQuery...
Edited version
load('/alertscript.php', function(xhr) {
var result = xhr.responseText;
// Execute the code
eval( result );
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}

Categories