php echod JavaScript won't run? - php

I have a problem where when I echo JavaScript from a PHP page to a HTML page using AJAX it won't run however, when I Inspect Element the JavaScript is there, I also echo some text and the text does show.
When I add the JavaScript manually in the HTML it works perfectly and the PHP, HTML and AJAX files are all in the same directory so there is no problem there.
I have 3 pages index.html, boo.php and ajax.js
index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/jquery.gritter.css" />
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load('jquery', '1.7.1');</script>
<script type="text/javascript" src="js/jquery.gritter.js"></script>
<script src="ajax.js"></script>
</head>
<body>
<script type="text/javascript"><!--
refreshdiv();
// --></script>
<div id="timediv"></div>
</body>
</html>
boo.php
<?php
// Fetch the data
$query = "SELECT * FROM $tablename";
$result = mysql_query($query);
// Return the results, loop through them and echo
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$name = $row['name']; // this equals Admin
if($name == 'Admin') {
echo $name; // this echos Admin and shows on index.html
// the javascript below doesnt
echo "
<script type='text/javascript'>
$(function(){
$(document).ready( function () {
var unique_id = $.gritter.add({
title: 'title text',
text: 'description text',
image: 'icon.jpg',
sticky: true,
time: '',
class_name: 'my-sticky-class'
});
return false;
});
});
</script>
";
}
}
?>
ajax.js
// Customise those settings
var seconds = 5;
var divid = "timediv";
var url = "boo.php";
////////////////////////////////
//
// Refreshing the DIV
//
////////////////////////////////
function refreshdiv(){
// The XMLHttpRequest object
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Timestamp for preventing IE caching the GET request
fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// The code...
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout('refreshdiv()',seconds*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
// Start the refreshing process
var seconds;
window.onload = function startrefresh(){
setTimeout('refreshdiv()',seconds*1000);
}
What the script is suppose to do check every 5 seconds if there is if there is a username in the database called Admin then show a gritter notification if there is.
Any ideas what I can do? thanks.

reverse your string notation on the second echo statement that doesn't work.
change double quote to a single qoute like this
echo "<script type='text/javascript'>
...more stuff...
title: 'title text',
...more stufff...
";
to
echo '<script type="text/javascript">
...more stuff..
title: "title text",
...more stuff...
';
why this works is because double quotes will look for variables inside the string and single quotes doesn't. so when you have $(document) this inside of the double quote php thinks its a var
EDIT: since the echo statement is working
the use of innerHTML method doesn't evaluate scripts it only evaluates html tags.
so if you want the response to evaluate the in coming echo statement use the jQuery function append()
that being said change
document.getElementById(divid).innerHTML=xmlHttp.responseText;
to
$('#divid').append(xmlHttp.responseText);

Related

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

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.

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.

Using jQuery function in AJAX

I have 3 PHP files named as,
index page
books
user
Index Page
<link href="colorbox.css" type="text/css" rel="stylesheet" media="all" />
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="jquery.colorbox.js"></script>
<script type="text/javascript">
function bookRetr(str)
{
if (str=="") {
document.getElementById("more-info").innerHTML="";
return;
}
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
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("more-info").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","showbook.php?id="+str,true);
xmlhttp.send();
}
</script>
<script>
$(document).ready(function() {
//Examples of how to assign the ColorBox event to elements
$(".popup").colorbox({iframe:true, innerWidth:750, innerHeight:520});
});
</script>
<div id='$bookid' onClick="bookRetr(this.id)></div>
<div id='more-info'></div>
bookshow.php
$bookid = $_GET['id'];
$query = mysql_query("SELECT * FROM bookdatabase WHERE ID='{$bookid}'");
$fetch = mysql_fetch_array($query);
$user = $fetch['userID'];
echo "<a href='showuser?id=$user' class='popup'>My name is X</a>";
The book show echo part is shown in my index page when i click on the div, but when click on My name is X, it open a new page but its actually supposed to open a popup. I got the popup named as colorbox plugin.
I'm unable to figure out where exactly i'm going wrong that the popup never opens.
Instead of:
$(".popup").colorbox({iframe:true, innerWidth:750, innerHeight:520});
Try:
$('.popup').live('click', function() {
$.colorbox({href:$(this).attr('href'), open:true, iframe:true, innerWidth:750, innerHeight:520});
return false;
});
OR if it won't work:
$("body").on("click", ".popup", function() {
$.fn.colorbox({href:$(this).attr('href'), open:true, iframe:true, innerWidth:750, innerHeight:520});
return false;
});
Hope it helps a little
your problem is that you are dynamically generating the link, You will have to use jquery live to make it work. Here is the code
$(function(){
//Examples of how to assign the ColorBox event to elements
$(".popup").live("click",function(){
$.colorbox({iframe:true, innerWidth:750, innerHeight:520});
return false;
});
});
Dins
Because you need to hijack the natural execution of clicking a href link...you need to add return false , which will essentially tell the browser to not treat your href like a link
If you change your popup function like this it should work, course readd your colorbox opts after the href opt by comma separation like so
$('.popup').click(function(){
$.colorbox({href:$(this).attr('href'), iframe:true, innerWidth:750, innerHeight:520});
return false;
});
Added your opts and code cleanup

Validating with Ajax

I wrote some ajax code that sends values to a php file for validation but I have a problem with it. This is my ajax code:
<html>
<body>
<style>
#displayDiv{
background-color: #ffeeaa;
width: 200;
}
</style>
<script type="text/javascript">
function ajaxFunction(str)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateChanged()
{
if(httpxml.readyState==4)
{
document.getElementById("displayDiv").innerHTML=httpxml.responseText;
}
}
var url="username_exists.php?username=";
httpxml.onreadystatechange=stateChanged;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
</head>
<body>
<input type="text"
onkeyup="ajaxFunction(this.value);" name="username" /><div id="displayDiv"></div>
</body>
</html>
and the above code send values to username_exists.php :
<?php
$username = trim($_REQUEST['username']);
if (usernameExists($username)) {
echo '<span style="color:red";>Username Taken</span>';
}
else {
echo '<span style="color:green;">Username Available</span>';
}
function usernameExists($input) {
// in production use we would look up the username in
// our database, but for this example, we'll just check
// to see if its in an array of preset usernames.
$name_array = array ('k','steve', 'jon', 'george', 'admin');
if (in_array($input, $name_array)) {
return true;
}
else {
return false;
}
}
?>
My problem is that when any username is put in the textbox returns "Username Available"! What did I do wrong?
You are sending an empty string as username to check thru your ajax call.
var url="username_exists.php?username=";
I would suggest you to start using jQuery to help you in handling this case.You don't need to worry about the cross browser issue and you dont need to write all these lines of code.
jQuery is a wonderful javascript library. http://www.jquery.com
Include jquery library (i will use the CDN Version) in your head section of HTML document and change your code like this.
HTML
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
<input type="text" id=txtUserName" />
</body>
javascript
$("#txtUserName").keyUp(function(){
if($("#txtUserName").val()!="")
{
$.ajax({
url: 'username_exist.php?username'+$("#txtUserName").val(),
success: function(data) {
alert(data);
}
});
}
}

Refresh PHP Page using ajax

I have a php page that needs to be refreshed every 5 secs. On embedding the ajax file, I don't find the updates taking place in Firebug. Here is the skeleton of the code:
**notification.php**
<?php
....
....
?>
<html>
<head>
<script src="./refresh.js"></script>
<script type="text/javascript">
refreshContents();
</script>
</head>
<body>
....
<div id="identifier">
<p>Waiting area</p>
</div>
</body>
</html>
**refresh.js**
var seconds = 5;
var content = "identifier";
var url = "notification.php";
function refreshContents()
{
var xmlHttp;
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(f)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(g)
{
alert("Browser not supports Ajax");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if (xmlHttp.readyState == 4)
{
document.getElementById(content).innerHTML = xmlHttp.responseText;
setTimeout('refreshContents()', seconds*1000);
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
var seconds = 5;
window.onload = function startrefresh(){
setTimeout('refreshContents()', seconds*1000);
}
Though it may not be the ideal solution, jQuery has a pretty simple way of implementing exactly this:
$(document).ready(function () {
function reload() {
$("#content").load("notification.php");
}
setTimeOut(reload, seconds*1000)
}
I'm not sure that will work perfectly, haven't done it in a little while, but its a much more elegant solution I do believe.
Why not just put a <meta http-equiv="refresh" content="5"> tag into your <head>? It will refresh the page every 5 seconds without the need for any javascript.
see the following example :
<html>
<head>
<title>Refresh a page in jQuery</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
<button id="PageRefresh">Refresh a Page in jQuery</button>
<script type="text/javascript">
$('#PageRefresh').click(function() {
location.reload();
});
</script>
</body>
</html>
this code definetly help you.
or we can use -
<meta http-equiv="refresh" content="5">

Categories