I need to find some tools to be able to call .php from .html.
Here is a problem:
while this example works, from .php file:
<html>
<head>
<meta http-equiv="content-type" content="text/html" charset="utf-8">
</head>
<body>
<p>Your IP is </p>
<?php
echo $_SERVER['REMOTE_ADDR'];
?>
<hr />
</body>
</html>
this example doesn't echoes IP in .html file:
---from index.html---
<html>
<head>
<meta http-equiv="content-type" content="text/html" charset="utf-8">
<script type="text/javascript">
function getIpNumber() {
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("showIpNumber").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","getip.php",true);
xmlhttp.send();
}
</script>
</head>
<body onload="getIpNumber();">
<p>Your IP is <span id="showIpNumber"></span></p>
</html>
---from getip.php---
<?php
echo "$_SERVER['REMOTE_ADDR']";
?>
what is wrong here?
Change this line
echo "$_SERVER['REMOTE_ADDR']";
to
echo $_SERVER['REMOTE_ADDR'];
having error reporting on would have signaled:
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /file.php on line 2
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
As pointed out by Knossos in a comment:
"You can also use echo "{$_SERVER['REMOTE_ADDR']}"; Although in this case, that would be quite pointless. It can be useful in bigger more complicated strings though."
Just replace this line
echo "$_SERVER['REMOTE_ADDR']";
to this
echo $_SERVER['REMOTE_ADDR'];
Related
I'm trying to learn Ajax (xmthttprequest). I wish to learn the basics of how to update parts of a webpage asynchronously. Here is my html code -
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AJAX Autocomplete</title>
<link rel="stylesheet" href="../sajawat/rti_css.css" />
<link rel="shortcut icon" href="#">
<script>
function ajaxText(str) {
xhttp = new XMLHttpRequest();
xhttp.open("GET", "ajaxproc.php?empName="+str, true);
xhttp.send(null);
xhttp.onreadystatechange=function () {
if(this.readystatechange==4 && this.status==200){
document.getElementById("changeTxt").innerHTML=xhttp.responseText;
console.log= xhttp.responseText;
}
};
}
</script>
</head>
<body>
<form name="simpleForm">
<fieldset>
<legend><strong>Practice</strong></legend>
<input type="text" id="fullName" name="empName" onkeyup="ajaxText(this.value)" />
<br />
<button>SUBMIT</button>
</fieldset>
</form>
<br />
<div id="changeTxt" style="display:block;">
Text should appear here.
</div>
</body>
</html>
I wish to write the response received from a php page to innerHTML of the div element having id as 'changeTxt'.
Following is my PHP code - (I know there are frameworks like JQuery but I wish to do this the old school way first.)
<?php
include '../some/database/connection/info/file';
$name = '%' . $_REQUEST["empName"] . '%';
try {
$getNameStmt = "SELECT emp_F_Name, emp_M_Name, emp_L_Name FROM emp_Table WHERE emp_F_Name LIKE '$name'";
$getName = $DBHandle->prepare($getNameStmt);
$getName->execute();
foreach ($getName as $fName) {
echo $fName['emp_F_Name'] . " " . $fName['emp_M_Name'] . " " . $fName['emp_L_Name'] . "<br />";
}
}
catch (PDOException $exception) {
echo "<br /><b>Error: " . $exception . "</b>";
}
?>
I have checked the php code. It is echoing the response lines properly.
I have checked using Firefox inspector that I am also getting responseText back.
But strangely, the responseText doesn't appear in console even if I use console.log=responseText line.
It goes without saying that nothing appears in the target div element at all.
What is going on here? Why I can't display the responseText despite receiving it ok??
Also I will be grateful if somebody could point me to some beginner-friendly material on how to use debugging tool provided in Firefox web developer tools. Thanks in advance.
I'm building a chat website and i want to add a sound alert whenever a new message is sent so i can alert other users for new unread messages(i use MySQL for storing messages etc.). I use ajax to get the messages from the database and put them on my chatbox. I tryied every way but it doesn't seen to work idividually on every NEW message. Please help!
That's my index.php
<?php
session_start ();
define('DB_HOST', 'localhost');
define('DB_NAME', '*******');
define('DB_USER','*****');
define('DB_PASSWORD','********');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<META HTTP-EQUIV="content-type" CONTENT= "text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Chat2Chat!</title>
</head>
<body id="body-color">
<?php
if (! isset ( $_SESSION ['user'] )) {
header ( "Location: sign-in.html" ); // Redirect the user
} else {
?>
<div id="wrapper">
<div id="menu">
<p class="welcome">
Καλωσήρθες, <b><?php echo $_SESSION['user']; ?></b>
</p>
<p class="logout">
<b class="submitmsg" id="exit" href="#">Logout</b>
</p>
<div style="clear: both"></div>
</div>
<div id="chatbox" class="chatbox">
</div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" size="63" autofocus/>
<input class="submitmsg" name="submitmsg" type="submit" id="submitmsg" value="Αποστολή"/>
</form>
</div>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
setInterval ( "get()", 2000 );
});
//jQuery Document
$(document).ready(function(){
//If user wants to end session
$("#exit").click(function(){
var exit = confirm("Είσαι σίγουρος πως θέλεις να αποσυνδεθείς;");
if(exit==true){window.location = 'index.php?logout=true';}
});
});
//If user submits the form
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
loadLog;
return false;
});
setInterval (loadLog, 2500);
function get(){
$.ajax({
type: 'GET',
url: 'chat.php',
success: function(data){
$("#chatbox").html(data);
var scroll = document.getElementById('chatbox');
scroll.scrollTop = scroll.scrollHeight;
}
});
}
</script>
<?php
}
?>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
The chat.php
<!DOCTYPE HTML>
<head>
<title>Chat</title>
<META HTTP-EQUIV="content-type" CONTENT= "text/html; charset=UTF-8">
</head>
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'db_57218');
define('DB_USER','u57218');
define('DB_PASSWORD','27222528');
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die("Failed to connect to MySQL: " . mysqli_error());
$query = "SELECT * FROM Messages";
if($result = mysqli_query ($con, $query)){
while ($row = mysqli_fetch_row($result))
{if($row['4']==0){
echo '('.$row['5'].') <b>'.$row['1'].'</b>: '.$row['2'].'<br>';
}
else{echo 'Ο χρήστης <b>'.$row['1'].'</b> '.$row['2'].'<br>';}
}
mysqli_free_result($result);
}
mysqli_close($con);
?>
You can store the last message id which you played sound for, and at every refresh action, you can check if the last message id is equals to id you stored before. If not, you play sound.
To be more clear:
$lastMessageId=5;
$lastMessageIdWePlayedSoundFor=4;
if($lastMessageId!=$lastMessageIdWePlayedSoundFor)
{
////play sound here
$lastMessageIdWePlayedSoundFor=$lastMessageId;
}
So whenever there is a new message we haven't played a sound for it's existance, we play sound. You can use this algorithm.
I'm developing a simple filter setup for a side project and have come up to a roadblock.
I'm using the following code to pass a variable to a second php file which does a database query based on the 'GET' variable that has been passed.
<?PHP
$con = mysql_connect("localhost","*********","***********");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("drwho", $con);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function updateCompanions(str)
{
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)
{
document.getElementById("randomStoryCompanionWrapper").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","updateCompanions.php?doctorID="+str, true);
xmlhttp.send();
}
</script>
<link rel="stylesheet" type="text/css" href="css/css.php" />
<link rel="stylesheet" type="text/css" href="css/css.css" />
<link rel="stylesheet" type="text/css" href="css/randomStory.css" />
<title>Doctor Who Thingy</title>
</head>
<body>
<section id="pageWrapper">
<header></header>
<section id="pageContent">
<section id="pageMainDisplay">
<section id="randomStoryDoctorWrapper">
<section class="randomStorySelectTitle">Doctor</section>
<?PHP
$dValue = 1;
$selectedDoctor = "";
$result = mysql_query("SELECT * FROM doctors ORDER BY doctorid");
while($row = mysql_fetch_array($result))
{
$doctorID = $row['doctorid'];
$doctorTitle = $row['doctorName'];
?>
<button class="randomStorySelectDoctorIcon" value="<?PHP echo $dValue;?>" onclick="updateCompanions(this.value);"><?PHP echo $doctorTitle;?></button>
<?PHP
$dValue++;
}
echo "<section class='end'></section>";
echo "</section>";
?>
<section id="randomStoryCompanionWrapper">
<section class="randomStorySelectTitle">Companion(s)</section>
<section class="randomStorySelectTitle">No Doctor selected</section>
<section class="end"></section>
</section>
<section id="randomStoryMonsterWrapper">
<section class="randomStorySelectTitle">Monster/Adversary</section>
<section class="randomStorySelectTitle"><?PHP echo $selectedDoctor; ?> </section>
<section class="end"></section>
</section>
</section>
<section id="pageAdDisplay">
<section id="pageGoogleAd">Google Ad space</section>
<section id="pageGoogleAd">Random Amazon Item</section>
<section id="pageGoogleAd">Random BBC Item</section>
<section id="pageGoogleAd">Random Big Finish Item</section>
<section id="pageGoogleAd">Random Comixology Item</section>
</section>
</section>
<footer>Footer</footer>
</section>
</body>
</html>
The problem I'm having is getting the 'GET' variable sent back to the original page.
ie. I need to have a new variable '$selectedItem' be populated with the value contained in the 'str' variable that the Javascript function is using.
In my head, it seems as though just assigning the 'GET' variable to the new variable in the 'updateCompanions.php' file would do it, but it doesn't seem to return the variable.
Would anyone know of how, or even if it is possible? (I know the difference between Javascript and PHP in terms of where the processing happens and that passing variables from Javascript to PHP is tricky :))
Thanks
Paul
Here is the code for updateCompanions.php
<?php
$con = mysql_connect("localhost","*********","*********");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("********", $con);
$doctorID = $_GET['doctorID'];
if (strlen($doctorID) < 2)
{
$doctorID = "0" . $doctorID;
}
echo "<section class='randomStorySelectTitle'>Companion(s)</section>";
$companions = mysql_query("SELECT * FROM companions WHERE companionDoctor LIKE '%$doctorID%' ORDER BY companionid");
while($row = mysql_fetch_array($companions))
{
$companionID = $row['companionid'];
$companionTitle = $row['companionTitle'];
echo "<button class='randomStorySelectCompanionIcon' value='" . $companionID . " onclick='updateMonsters(this.value);>" . $companionTitle . "</button>";
}
echo "<section class='end'></section>";
?>
I have a button that allows authentication from twitter, everything works properly, but the only issue is that i wish to open the login-twitter.php page on a different tab, i tried using window.open in place of header but it didn't work. can anyone tell how it can be done
<?php
ob_start();
session_start();
if (isset($_SESSION['id'])) {
header("location: u_tasks.php");
}
if (array_key_exists("login", $_GET))
{
$oauth_provider = $_GET['oauth_provider'];
if ($oauth_provider == 'twitter')
{
header("Location: login-twitter.php");
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<?
echo "<div class='col-md-9'>";
echo "<a href='?login&oauth_provider=twitter'><button style='background-color:#1dcaff; border-color:#1dcaff; color:white; height:30px; border-radius:10px;'>Go To Twitter</button></a>";
echo "</div>";
?>
</body>
</html>
i think it is helpful to you.
<button style='background-color:#1dcaff; border-color:#1dcaff; color:white; height:30px; border-radius:10px;'>Go To Twitter</button>
using header("Location:..."); can only do redirects. As far as I know, you'll have to do some amount of javascript or html to achieve your goal. Another problem is that browsers like to block automatically opened popups because 99% of the time automatic popups are used only by spammers. However, I'll show you a way to attempt to do this anyways:
<?php
$usingTwitter=0;
ob_start();
session_start();
if (isset($_SESSION['id'])) {
header("location: u_tasks.php");
}
if (array_key_exists("login", $_GET))
{
$oauth_provider = $_GET['oauth_provider'];
if ($oauth_provider == 'twitter')
{
$usingTwitter=1;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
<?php
if($usingTwitter){
echo "window.open('login-twitter.php');";
}
?>
<script>
</head>
<body>
<?
echo "<div class='col-md-9'>";
echo "<a href='?login&oauth_provider=twitter'><button style='background-color:#1dcaff; border-color:#1dcaff; color:white; height:30px; border-radius:10px;'>Go To Twitter</button></a>";
echo "</div>";
?>
</body>
</html>
Make sure you turn off popup blocking in your browser for this to work though!
Here is my JS function:
function checkError() {
var field = 'error';
var url = window.location.href;
document.write('test');
window.alert('please work');
if(url.indexOf('?' + field + '=') != -1)
document.write('The username and password do not match. Do not use your full email.');
return true;
}
and then in my body paragraph I have:
<?php echo '<script> checkError();</script>' ?>
It doesn't have any errors calling it. But the function does nothing on my page. Any thoughts? I've tried putting the JS script in the page and in a JS file and correctly called for its inclusion.
Full script:
<html>
<head>
<meta charset="UTF-8">
<title>Secure Login</title>
<script type="text/JavaScript" src="js/functions.js"></script>
<link href="stylesheets/mainStyle.css" rel="stylesheet" type="text/css">
<link href="stylesheets/formStyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php include('header.php'); ?>
<div id="mainContent">
<h1>Member Login</h1>
<div id="mainParaText">
<?php echo '<script> checkError();</script>' ?>
</div>
</body>
</html>
TURNS OUT JS Function is UNDEFINED. Ugh, can't figure out why (thought I fixed this problem a while back lol)
try like this:
<html>
<head>
<meta charset="UTF-8">
<title>Secure Login</title>
<script type="text/JavaScript" src="js/functions.js"></script>
<link href="stylesheets/mainStyle.css" rel="stylesheet" type="text/css">
<link href="stylesheets/formStyle.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
function checkError(){
var field = 'error';
var url = window.location.href;
document.write('test');
window.alert('please work');
if(url.indexOf('?' + field + '=') != -1)
document.write('The username and password do not match. Do not use your full email.');
return true;
}
<?php
echo "checkError();";
?>
</script>
</head>
<body>
<?php include('header.php'); ?>
<div id="mainContent">
<h1>Member Login</h1>
<div id="mainParaText">
<?php echo '<script> checkError();</script>' ?>
</div>
</body>
</html>
JS is client side and PHP is server side.
That means that everything in PHP code will be processed on server and then "echoed" to your browser where you get undefined error.
When debugging this you should always check source code in the browser first so you see exactly what your server echoed.
I'm guessing a bit but try with double quotes instead of single.
And not related to the question ...
You are checking username and password with JS? How exactly will you do this? With ajax call back to the server? If you check with JS that means password should be in the source code somewhere and that is NOT secure. Username / pass validation should always be made on serverside (either with ajax request or usual submit form).