Unable to show prompts or alerts using echo in php [duplicate] - php

This question already has answers here:
Can scripts be inserted with innerHTML?
(26 answers)
Closed 5 years ago.
I tried to use a simple echo function with JS in it to show alerts and prompts, in a php page which is called using AJAX. I looked at lot of other SO posts, but couldn't find any working solution, like this one. Here is my code:
//AJAX
function callPhp(opt, algorithm, arrayReq, solArrayReq) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("debug").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "selectknown.php?q="+opt+"&alg="+algorithm, true);
xmlhttp.send();
And
//selectknown.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<?php
echo '
<script type="text/javascript">
alert("Hello world! This is an Alert Box.");
var accepted = prompt("enter the letters \'yes\' here");
</script>
';
?>
</body>
</html>

No need to echo the script out, just use it as html.
//selectknown.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
alert("Hello world! This is an Alert Box.")
</script>
</body>
</html>

Firstly, if you wish to put a script tag in an echo statement, it is possible. I think your problem is that you are running the code as a .html file instead of running it as a .php file. Just name the file something like file_loader.php
The code needs to run on a server. PHP is a server side scripting language.
Or you could copy and paste the code below into a php playground to quickly see it working.
<html>
<head>
<body>
<?php
echo '
<script type="text/javascript">
alert("Hello world! This is an Alert Box.");
var accepted = prompt("enter the letters \'yes\' here");
</script>
';
?>
<div id='debug'>Waiting for file to load.....</div>
<script>
//AJAX
function callPhp(opt, algorithm, arrayReq, solArrayReq) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("debug").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "selectknown.php?q="+opt+"&alg="+algorithm, true);
xmlhttp.send();
</script>
</body>
</html>
Secondly, in order to load the file from the ajax code, you need to add an element that is identified by the specified Id - debug e.g.
<div id='debug'>Waiting for file to load.....</div>
Hope you find that helpful.

Related

JavaScript / PHP / Ajax set multiple session variables

Hello friends a newbie question. I am new to programming hence please be gentle.
I am trying to post multiple session variables using JavaScript so that I can use them later in my PHP at multiple places.
My index.php file
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<?php
if ((empty($_SESSION['function1Val'])) & (empty($_SESSION['function2Val'])) && (empty($_SESSION['jsStatus']))) {
echo '<script type="text/javascript" src="vals.js"></script>
<script type="text/javascript">
var session=false;
var jsStatus;
var function1Val;
var function2Val;
</script>';
} else {
echo '<script type="text/javascript">
var session=true; var jsStatus=' . $_SESSION['jsStatus'] . ';
var session=true; var function1Val=' . $_SESSION['function1Val'] . ';
var session=true; var function2Val=' . $_SESSION['function2Val'] . ';
</script>';
}
?>
</head>
<body>
<?php
echo $jsStatus;
echo $function1Val;
echo $function2Val;
session_destroy ();
?>
</body>
</html>
My vals.js file
window.onload = function() {
// if there is no session (session = false)
if (!session) {
// Set value to variable jsStatus
jsStatus = 'enabled';
// Call function to get function1
function1();
// Call function to get function2
function2();
// Make ajax call to php page to set the session variable
setSession();
}
}
function function1() {
// code to get value goes here
function1Val = 'result1';
}
function function2() {
// code to get value goes here
function2Val = 'result2';
}
function setSession() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// Reload the page
window.location.reload();
}
}
xmlhttp.open("POST","session.php?function1Val=" + function1Val,true);
xmlhttp.send();
// like this I want to transfer other values of 'function2Val' and 'jsStatus'
}
My session.php file
<?php
session_start();
// check if it is already set if you like otherwise:
$_SESSION['function1Val'] = $_REQUEST['function1Val'];
$_SESSION['function2Val'] = $_REQUEST['function2Val'];
$_SESSION['jsStatus'] = $_REQUEST['jsStatus'];
?>
I know the code is messy but I don't know how to write the correct syntax. I actually tried to modify a single variable code but failed. hence need help.
The idea is to post various values derived out of various JavaScript functions to the session for use by PHP.
Please help.
UPDATE:
It has to be this way as the values to the said variables can be calculated with the help of JavaScript only.
You have to concatenate the parameters with an ampersand (&).
Use this line
xmlhttp.open("POST","session.php?function1Val=" + function1Val+"&function2Val=" + function2Val+"&jsStatus=" + jsStatus,true);
BTW: I would really suggest to use jQuery or a similar library for AJAX requests. Furthermore I would use JSON for exchanging the data or a Javascript array where the key names are those of the variables.

Ajax and setInterval() to auto update text file is not updating

I have two text files that are being display on a web page through ajax. I need these two files to update as soon as more text is added to the text file. When I completed this script I tested it on my localhost and all was working properly. Now I have attempted to get it to work on my web host and the text is displaying, but when it is time to update the files nothing updates.
I tried disabling the caching of the ajax response, but the files still do not update.
Here is the code:
<html>
<head>
<script>
$.ajaxSetup ({
cache: false
});
function UpdateDAU()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("UpdateD").innerHTML=xmlhttp.responseText.split('\n').join('<br/>';
}
}
xmlhttp.open("GET","../logs/dau.txt",true);
xmlhttp.send();
}
function UpdateFireBox()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("UpdateF").innerHTML=xmlhttp.responseText.split('\n').join('<br/>');
}
}
xmlhttp.open("GET","../logs/firebox.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<script type="text/javascript">
UpdateDAU();
</script>
<div id="UpdateD">No Logs</div>
<script type="text/javascript">
setInterval("UpdateDAU", 1000);
</script>
<script type="text/javascript">
UpdateFireBox();
</script>
<div id="UpdateF">No Logs</div>
<script>
setInterval("UpdateFireBox", 1000);
</script>
</body>
</html>
Is there something that needs to be changed on the server or is this an issue with my code?What am I doing wrong?
After researching for the past week I finally have the display updating properly.
I could not get the files to update from the text file, so I had to echo the files from a php file before the ajax displayed it.
This is the code that is working on multiple machines:
<html>
<head>
<script>
$.ajaxSetup ({
// Disable caching of AJAX responses */
cache: false
});
function UpdateDAU()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("UpdateD").innerHTML=xmlhttp.responseText.split('\n').join('<br/>');
}
}
xmlhttp.open("GET","getdau.php",true);
xmlhttp.send();
setTimeout(function() {
UpdateDAU();
}, 1000)
}
function UpdateFireBox()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("UpdateF").innerHTML=xmlhttp.responseText.split('\n').join('<br/>');
}
}
xmlhttp.open("GET","getfirebox.php",true);
xmlhttp.send();
setTimeout(function() {
UpdateFireBox();
}, 1000)
}
</script>
</head>
<body>
<script type="text/javascript">
UpdateDAU();
</script>
<div id="UpdateD"><p class="text-warning">If there is no page...<br> Then the guards have not started there rounds.</p></div>
<script type="text/javascript">
UpdateFireBox();
</script>
<div id="UpdateF"><p class="text-warning">If there is no page...<br> Then the guards have not started there rounds.</p></div>
</body>
</html>
Here is the PHP files used to diplay files:
<?php
$file = file_get_contents('../logs/dau.txt', true);
echo $file;
?>
and second PHP file is the same:
<?php
$file = file_get_contents('../logs/firebox.txt', true);
echo $file;
?>
Using this code the logs inside txt files are updated and displayed every second without refreshing the page.
If there is a way to use these same steps but with only 1 php file instead of 2 show me and I will delete my answer and select yours.

how to make java script run on the element returned by AJAX

My problems is how can I make my java script run on the elements that returned by AJAX. The javascript does not work on the that returned by AJAX. In my script it suppose to pop out a dialog box with "Hello" but its not. How can I make it works or there are another ways for this? Thanks for the advice.
The below is my code...
index.html
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#box_1").on("click", function() {
alert("Hello!");
});
changeDisplay();
});
function changeDisplay() {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("text").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","ajaxHandling.php",true);
xmlhttp.send();
};
</script>
</head>
<body>
<h1>Ajax Test</h1>
<div id="text">
</div>
</body>
</html>
ajaxHandling.php
<?php
echo '<div id="box_1" class="box">Click me</div>';
?>
A common problem, you need to use the correct on() syntax for future elements by binding it to a parent of the future element that exists at the time the script runs.
$(document).on("click", "#box_1", function() {
alert("Hello!");
});
I've used document, but using the closest existing parent is better. Example:
$("#wrapper").on("click", "#box_1", function() {
alert("Hello!");
});
My short answer is that you need to bind the click event slightly differently, using jQuery.on:
$('#text').on('click', '#box_1', function() {
alert('Hello!');
});
This binds the click event dynamically to any item within the #text element (or that is added later to the #text element) that matches your #box_1 selector.
My long answer is that if you are using jQuery, you should also take advantage of its AJAX library rather than roll your own.
$.ajax({
url: '/ajaxHandling.php',
}).done(function ( data ) {
$('#text').html(data);
});

AJAX not working PHP

I am trying to retrieve an xml file from the server via ajax, but cannot get it to parse. I do not know what I am doing wrong. When I call the getFriends.php, it prints the xml fine. here is the ajax code:
<!DOCTYPE>
<html>
<head>
<title>Ajax Sample</title>
<script type="text/javascript">
function getFriendsList(MemberId) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var xmlDoc = xmlhttp.responseXML;
var friendElements = xmlDoc.getElementsByTagName('friend');
for (var x=0; x<friendElements.length; x++) {
// We know that the first child of show is title, and the second is rating
var id = showElements[x].childNodes[0].value;
var name = showElements[x].childNodes[1].value;
// Now do whatever you want with the show title and ratings
document.write("hi");
}
}
}
xmlhttp.open("POST","getFriends.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("id=" + MemberId);
}
</script>
</head>
<body>
<input name="ajax" type="button" onClick="getFriendsList(1)" value="Click for AJAX">
<div style="background-color:#00FF99;" id="placehere">Here is where the update will occur.</div>
</body>
</html>
and here is the getFriends.php code (user class works fine):
<?php
include('lib.php');
//$id = $_POST['id'];
$id=1;
$user = new User($id);
echo $user->getFriendsList();
?>
You have undefined variable 'showElements' in your for loop. These two lines:
var id = showElements[x].childNodes[0].value;
var name = showElements[x].childNodes[1].value;
should be replaced with:
var id = friendElements[x].childNodes[0].value;
var name = friendElements[x].childNodes[1].value;
using jquery to perform ajax calls is easy and hassle free see http://api.jquery.com/jQuery.ajax/ for more info

AJAX xmlHttp request GET undefined Index XML read file

I am getting an undefined index error message on server side when i am trying to send a value selected from a dropdown box on client side (javascript/AJAX) to server side (php). I have a feeling that the GET on the client side is not sending the url correctly or if it is it is sending the value as null.
Does anyone have any idea how to solve this issue.
The code on the client is:
<title>test</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$.getJSON("process.php", function(fileName)
{
for(var i in fileName)
{
fileName[i] = fileName[i].split("../Test/").join("")
fileName[i] = fileName[i].split(".xml").join("")
document.dropDown.file[i]= new Option(fileName[i],"../Test/"+fileName[i]+".xml", false)
}
});
});
var xmlhttp;
function getFile(str){
alert("xmlprocess.php?filename="+str);
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange= response(file);
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","xmlprocess.php?filename="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form name = "dropDown">
<Select name = "file" onclick = "getFile(str1)" onchange = "str1 = this.options[this.selectedIndex].value"></Select>
</form>
<div id="txtHint"></div>
</html>
and the code on the server side is :
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$br = "<br>";
$filename = $_GET["filename"];
echo $filename;
?>
Ok guys ive found the answer
i had to change the onreadystatechange to be equal to a function on client side as shown below
xmlhttp.onreadystatechange= function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML= xmlhttp.responseText;
}
};

Categories