Unable to execute PHP code from extenal file with GET request - php

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

Related

PHP sends answer twice

I have some experience with Nodejs so I wanted to try some php too.
I want to make a GET request in a php file and get a response. While I get data, I receive them twice. I cheked the network tab on my browser and I see only one request. The html/javascript code works without a problem on nodejs, php persists on sending data twice. Why does this happen?
Html file:
<html>
<head>
<title>Hello World</title>
</head>
<body>
<p>Hello User!!</p>
<button id="button">Get Request</button>
</body>
<script>
document.getElementById("button").onclick = function () {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php?id=HI", true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 || this.status === 200) {
console.log(this.responseText);
}
};
xmlhttp.send();
};
</script>
</html>
test.php file:
<?php
ini_set('display_errors', 1);
$id = $_GET["id"];
if($id == "HI"){
echo ("Noice!");
}else {
echo ("I am sowwy :3");
}
?>
Disclaimer: "I understand this code does nothing important and always sends the same response. It is just an experiment to get myself familiar with php".
Thanks for your time.
You are not sending the responset twice but logging it twice.
onreadystatechange should be:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
if (this.status === 200) console.log(this.responseText);
}
};

Display file info?

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);

Ajax add input more than once

I've successfully wrote a working Ajax code, but the problem is that i can add an input field only once. I have a submit input, that calls Ajax script, everything works, the input text field appears, but after this if i want to add another text field by clicking on the submit input, it does not work. You only load once (YOLO). How do i write more awesome code that lets me add as many text fields as needed? Thanks for every reply. Here is my code:
index.php:
<head>
<script>
function ajaxobj(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('asd').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'ajaxAddInput.php',true);
xmlhttp.send();
}
</script></script>
</head>
<body>
<input type="submit" onclick="ajaxobj();">
<div id="asd"></div>
</body>
the php file:
<?php
echo '<input type=\"text\">';
?>
Simply use a standardized library, just like jQuery. With this in mind, you might use the following code:
$("#asd").on('change', function() {
var val = $(this).val();
$.ajax("ajaxAddInput.php", {input: val});
});
Alternatively, you can use the library with classes as well:
$('input[type=text]').on('change', function() {
var val = $(this).val();
$.ajax("ajaxAddInput.php", {input: val});
});

Changing div content with time

I am trying to load a php file after a while by using ajax. What I am trying to do is kind of a quiz. I want an image screen to be seen by user for 3 seconds and then the answer choices to be seen. I want to do this for 3 or 4 times in a row. For example;
1)The question image
after a few seconds
2)Answer Choices
After click on an answer
3)Second question image
... and go on with this order.
I can do this with below code:
<script type="text/javascript">
var content = [
"<a href='resim1a.php'> link 1 </a>",
"<a href='resim2a.php'> link 2 </a>",
"insert html content"
];
var msgPtr = 0;
var stopAction = null;
function change() {
var newMsg = content[msgPtr];
document.getElementById('change').innerHTML = 'Message: '+msgPtr+'<p>'+newMsg;
msgPtr++;
if(msgPtr==2)
clearInterval(stopAction);
}
function startFunction() { change(); stopAction = setInterval(change, 500); }
window.onload = startFunction;
</script>
<div id="change" style="border:5px solid red;width:300px; height:200px;background-Color:yellow"> </div>
But, when this file is included by another file, this script does not work. How can I make it work?
<script type="text/javascript">
function load(thediv, thefile){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject ('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile , true);
xmlhttp.send();
}
</script>
The previous page script is above. I use this script with the below code:
<div id="anotherdiv" >
<input type="image" onclick="load('anotherdiv' , 'include.php');"src="buton1.png">
</div>
The reason is because you are expecting the window to fire onload event:
window.onload = startFunction;
Window is loaded when the ajax is running, so why not call the function directly?
startFunction();
If you need some DOM elements before the script, just put the script below the DOM elements and the script will run after the DOM is ready.
you need to remove change(); from function startFunction()
here is the full example click here
I hope it will help for you.

AJAX To Call and Run PHP Script

I have a working PHP script on my server and a HTML page with JavaScript and AJAX which I would like to call and run the PHP script. However, the AJAX responseText is displaying all the PHP code rather than running it. What do I need to do to only get the results of the PHP? Other examples I looked at used the responseText and it seemed to work out well, but not for me :(
Thanks,
elshae
My AJAX code is below...my PHP works fine, it has been tested :)
function ahah(url) {
//document.getElementById(target).innerHTML = ' Fetching data...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
var div = document.createElement('DIV');
div.innerHTML = req.responseText;
document.getElementById('chicken_contentDiv').appendChild(div);
} else {
" <div> AHAH Error:\n"+ req.status + "\n" +req.statusText + "</div>";
}
}
}
function load(name) {
ahah(name);
return false;
}
<div> + load('./getFiles.php') + </div> //called in a div
Ok here is the new code:
//Some stuff happens here, IMO think it's irrelevant to this issue...
//This is where the AJAX/JQuery calls the php
var info = new OpenLayers.Control.WMSGetFeatureInfo({
url: 'http://localhost:8080/geoserver/wms',
title: 'Identify features by clicking',
queryVisible: true,
eventListeners: {
getfeatureinfo: function(event){
map.addPopup( new OpenLayers.Popup.AnchoredBubble(
"chicken",
map.getLonLatFromPixel(event.xy),
null,
event.text + '<div> Hello Tibet :)</div>' + $('#chicken_contentDiv').load('http://localhost/mapScripts/getFiles.php'), //have also tried localhost:80, no diff
null,
true
));
}
}
});
map.addControl(info);
info.activate();
});
To your apache config or .htaccess file add this line AddType application/x-httpd-php .html so html files will be parsed with php interpreter.
Are you missing the <?php at the beginning of your getFiles.php file?
If the response contains actual PHP code, then it is not being processed by the PHP interpreter. Where are you running this? It is obvious that the web server is not properly configured to process PHP files.
EDIT:
The line you have:
event.text + '<div> Hello Tibet :)</div>' + $('#chicken_contentDiv').load('http://localhost/mapScripts/getFiles.php'),
is incorrect.. you don't want to append the outcome of the jQuery function. The output would always be an object. You just want to run that script, which would populate a DIV with an ID of chicken_contentDiv. (is that really the right DIV to put the details in?)
It should be at the end, after your var info declaration is closed and done.

Categories