Changing site title server-side - javascript

How can I change a web page title for everyone on that site and not to be changed with refreshing, using javascript or PHP?
I've tried HTML DOM title but it gets back to its first title after refreshing.
I've tried giving variable in PHP and changing it by after a button pressed but the title didn't change!
These were my codes:
<?php
$title = "Chat";
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<div id="chat_messages"></div>
<form enctype="multipart/form-data" method="post">
<input onClick="dokme()" class="button2" type="submit" name="send" value="Send">
</form>
</div>
<?php
if(isset($_POST['send'])){
$title = "new message";
}
?>
</body>
</html>
Any idea what should I do?

Glad to help.
Of course the title won't change, because php reads your code from 1st line to the end, and you have already added $title = "Chat";
what to do is to change the code like this:
<?php
if(isset($_POST['send'])) $title = "new message";
else $title = "Chat";
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<div id="chat_messages"></div>
<form enctype="multipart/form-data" method="post">
<input onClick="dokme()" class="button2" type="submit" name="send" value="Send">
</form>
</div>
</body>
</html>
This will change the title.
Also, if you want to change the title without refreshing the page, you need JS.
Just use
document.title = '***'; //use your title to replace "***"!
Have a good day~

There are some mistakes in your code like you have used onClick instead you should use onclick
you have not putted a semicolon ; while you are typing
You have not assigned action to your form
Action will be echo htmlspecialchars($_SERVER['PHP_SELF'])
And we will use if else
This will work
<?php
if (isset($_POST['send'])) {
$title = "new message";
} else {
$title = "Chat";
}
?>
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<div id="chat_messages"></div>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" enctype="multipart/form-data" method="post">
<input onclick="dokme()" class="button2" type="submit" name="send" value="Send">
</form>
</div>
</body>
</html>
I hope this will Help you

Related

How to pass PHP variable value to html input box from external PHP file?

HTML FILE
<body>
<input type="text" id="name" class="form-control" name="name">
<label for="name">name</label>
<script type="text/javascript" src="PHPfile.php"></script>
</body>
Separate PHP FILE
I have done MySQL query, and I have query value in $row['name'].
How can I put this value in the HTML input box?
<?PHP
**some code here**
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
echo "<script>
var name = <?php echo $row['name'] ?>;
document.getElementById(name).value='name';
window.location.href='htmlpage.html';
</script>";
?>
I tried this but this didn't work. I got the following error
Parse error: syntax error, unexpected string content "", expecting "-" or identifier or variable or number in...
I have tried to provide custom variable to var name and then document.getElementByID line. Still, it doesn't work.
Any Solution?
This should work.
<?php
/**some code here**/
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
echo '<script>
document.getElementById("name").value = "' . $row['name'] . '";
</script>';
?>
or same thing if more complex HTML/script needed:
<?php
/**some code here**/
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
?>
<script>
document.getElementById("name").value = "<?=$row['name'];?>";
</script>
<?php
/* more php code */
?>
If you still get the same error message, than the problem is somewhere else.
To echo a variable in a string ( in php ) we can use concatenation " . " $var['code'] ". " or template string { $var["code"] }
PHPfile.php
<?php
$row = ["name" => "something"];
echo "
let input = document.getElementById('name');
input.value = '{$row['name']}';
setTimeout(()=>{
window.location.href='htmlpage.html';
} ,2000)
"
?>
For echoing variables in string use {$var} instead of simple concatenation
Extended answer
index.php
<?php
// all querys here ... getting results from db
// assuming result
$row = [
"username" => "xxxxxxxxx",
"email" => "xxxxx#example.com"
];
$name = $row['username'];
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width , initial-scale=1.0">
<title>Damn Forms ! </title>
</head>
<body>
<form action="file.php" method="post" accept-charset="utf-8">
<label for="name">Name <span class="red">*</span></label>
<input type="text" id="name" class="form-control" name="name" placeholder="Enter your full name " value="<?= $name ?>">
<!-- sending values to another php file -->
<button type="submit">Submit</button>
</form>
</body>
</html>
file.php
<?php
if($_SERVER["REQUEST_METHOD"] === "POST"){
$name = $_POST['name'];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width">
<title>Input Form </title>
</head>
<body>
<input type="text" name="name" id="" value="<?= $name ?>" />
</body>
</html>
I see 2 answers already, but my way of doing it would be....
HTML
<body>
<input type="text" id="name" class="form-control" name="name">
<label for="name">name</label>
<div id="externalPHP"></div>
<script type="text/javascript">
document.getElementById("externalPHP").innerHTML='<object type="type/php" data="PHPfile.php" ></object>';//javascript
$('#externalPHP').load('PHPfile.php');//jQuery
</script>
</body>
The php file
<?PHP
**some code here**
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
echo '<script>document.getElementById("name").value='."$row['name']".';</script>';
?>

How to preserve newlines in a textarea when passing by POST?

In my web page, I am passing the value of a textarea to PHP via the POST Method. That value is supposed to be written into a file, but in the $_POST key which contains the value, it has no line breaks, so when it is written to the file, there are no line breaks (as if some one replaced \n with nothing).
Is there some PHP/JS function that replaces JS textarea newlines into PHP newlines that work in files?
Edit:
My code is supposed to be a file editor. Here it is:
<!DOCTYPE html>
<html>
<head>
<title>File Editor</title>
<meta charset="UTF-8"/>
<style>h1{text-align:center;font-size:40px;padding:10px;border:2px solid black;border-radius:10px;}textarea{width:90%;height:90%}</style>
</head>
<body>
<h1>File Editor</h1>
<?php
if(isset($_POST["save"],$_POST["extra"]))
file_put_contents($_POST["save"],$_POST["extra"]);
if(isset($_POST["delete"]))
unlink($_POST["delete"]);
if(!isset($_POST["filename"],$_POST["submit"])){
?>
<form action="editor.php" method="post">
<label for="filename" id="n">Enter a file to edit: </label>
<input type="text" name="filename" placeholder="Enter file name to edit"/>
<button type="submit" name="submit">Submit</button>
</form>
<?php }else{ ?>
<textarea><?php echo htmlspecialchars(file_get_contents($_POST["filename"])); ?></textarea>
<span style="display:none"><?php echo $_POST["filename"]; ?></span>
<form action="editor.php" method="post" style="display:none" id="a">
<input name="close" id="v" />
<input name="extra" id="e" />
</form><br/>
<button id="save">Save</button>
<button id="close">Close file</button>
<button id="delete" style="color:red">Delete file</button>
<script>
function submit(v,x,c){
document.getElementById("v").name=v;
document.getElementById("v").value=x;
document.getElementById("e").value=c;
document.getElementById("a").submit();
}
document.getElementById("save").onclick=function(){
submit("save",document.getElementsByTagName("span")[0].innerHTML,document.getElementsByTagName("textarea")[0].value.replace(/\n/g,"\r\n"));
}
document.getElementById("close").onclick=function(){submit("close");}
document.getElementById("delete").onclick=function(){
if(confirm("Are you sure you want to delete this file?"))submit("delete",document.getElementsByTagName("span")[0].innerHTML);
}
</script><br/><br/>
<?php } ?> </body>
</html>
I see that the purpose of your javascript code is only to fill in any input values. This can be done by utilizing <form> directly. Most likely, copying your data into a <input tye="text"> (text is the default type) will mangle your newlines.
Something like this should be equivalent and without the presented issue:
<!DOCTYPE html>
<html>
<head>
<title>File Editor</title>
<meta charset="UTF-8"/>
<style>h1{text-align:center;font-size:40px;padding:10px;border:2px solid black;border-radius:10px;}textarea{width:90%;height:90%}</style>
</head>
<body>
<h1>File Editor</h1>
<?php
if(isset($_POST["save"],$_POST["extra"]))
file_put_contents($_POST["filename"],$_POST["extra"]);
if(isset($_POST["delete"]))
unlink($_POST["filename"]);
if(!isset($_POST["filename"],$_POST["submit"])){
?>
<form action="editor.php" method="post">
<label for="filename" id="n">Enter a file to edit: </label>
<input type="text" name="filename" placeholder="Enter file name to edit"/>
<button type="submit" name="submit">Submit</button>
</form>
<?php }else{ ?>
<span style="display:none"><?php echo $_POST["filename"]; ?></span>
<form action="editor.php" method="post">
<textarea name="extra"><?php echo htmlspecialchars(file_get_contents($_POST["filename"])); ?></textarea>
<br/>
<input type="hidden" name="filename" value="<?= $_POST['filename'] ?>">
<button name="save">Save</button>
<button name="close">Close file</button>
<button name="delete" style="color:red">Delete file</button>
</form>
<script>
document.getElementById("delete").onclick=function(e){
if(!confirm("Are you sure you want to delete this file?")) e.preventDefault();
}
</script>
<br/><br/>
<?php } ?>
</body>
</html>
Also as mentioned, you will probably need to format the newlines for html when displaying.
When needing to pass the same or hidden data you can use <input type="hidden" name=".." value="..">. This is used to pass the filename. The desired action is passed with the button press. The name of button you press will be passed in the request.
In your PHP code, you can do:
$text = nl2br($_POST['name_of_textarea']);
Then save $text into the file.
This will preserve line breaks.

How to merge two php page into one php

I have index.php and upload.php. index.php gives option of selecting an image and once clicked on upload image button, upload.php is called which then creates a directory and saves the image.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Face Recognition</title>
<link href="main.css" rel="stylesheet" type="text/css" href="" />
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Select file: <input name="userfile" type="file" />
<?php $file = isset($filename) ? $filename : ''; ?>
<input type="text" name="filename" value="<?php echo $file; ?>" />
<input type="submit" value="Upload Images" />
</form>
</body>
</html>
upload.php
<?php
$uploaddir = 'G:/dataset/' . $_POST['filename'] . "/";
// check if directory exists
if(!is_dir($uploaddir)){
mkdir($uploaddir);
}
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']) ;
echo $uploadfile;
move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadfile);
?>
When upload.php is called, the page redirects to upload.php page and shows the upload file path. I dont want to redirect to upload.php. I want to keep everything in single index.php file. So that after uploading the images, it shows the upload file path on the same index.php. How can we achieve it.?
Put both in one PHP page and set the action of your form to the page itself. it would do the trick :)
<!DOCTYPE html>
<html>
<head>
<title>Face Recognition</title>
<link href="main.css" rel="stylesheet" type="text/css" href="" />
</head>
<body>
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Select file: <input name="userfile" type="file" />
<?php $file = isset($filename) ? $filename : ''; ?>
<input type="text" name="filename" value="<?php echo $file; ?>" />
<input type="submit" value="Upload Images" />
</form>
</body>
</html>
<?php
if(!empty($_FILES['userfile']))
{
$uploaddir = 'G:/dataset/' . $_POST['filename'] . "/";
// check if directory exists
if(!is_dir($uploaddir)){
mkdir($uploaddir);
}
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']) ;
echo $uploadfile;
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile);
}
?>
You can achieve that by using the functionality of PHP_SELF environment variable.
You have to make the action attribute as form action = <?php echo $_SERVER['PHP_SELF']; ?> and then add the code of upload.php into the same index.php.
For reference : Refer this link

Styling text by outputted document.write

I have a login php form, when the user types the incorrect credentials then it will output "Incorrect Username or Password" however this is put right at the top of the website above the navigation. Here is a screenshot : http://imgur.com/IAsaMWH
I would like to have the text placed inside the website wrapper and within a div so that i can edit it with css.
I have tried using document.getElementById('log').innerHTML however this only works when the div "log" is above the php code, however the php has to stay at the top because otherwise I get a error:
Warning: session_start(): Cannot send session cache limiter - headers
already sent
Here is my php/js
In short, all i would like to do is when the login credentials are wrong a message is shown to the user "Incorrect Username or Password" This message i need to be editable with CSS, as i need to reposition it on the page.
If anybody would please be able to edit my code and explain to me what they have done - it would be hugely appreciated.
Here is my PHP with JS:
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_SESSION['user'])!="")
{
header("Location: account.php");
}
if(isset($_POST['btn-login']))
{
$email = mysql_real_escape_string($_POST['email']);
$upass = mysql_real_escape_string($_POST['pass']);
$res=mysql_query("SELECT * FROM users WHERE email='$email'");
$row=mysql_fetch_array($res);
if($row['password']==md5($upass))
{
$_SESSION['user'] = $row['user_id'];
header("Location: account.php");
}
else
{
?>
<script>document.write('Incorrect Username or Password');</script>
<?php
}
}
?>
Here is my HTML
<?php include"authentication/login.php";?>
<!DOCTYPE html>
<html>
<HEAD>
<title>Website | Loign</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<?php include "includes/page_sources.php"; ?>
</HEAD>
<body>
<?php include "includes/navigation.php"; ?>
<div id="wrapper">
<div id="login-form">
<form method="post">
<input type="text" name="email" placeholder="Your Email" required />
<input type="password" name="pass" placeholder="Your Password" required />
<button type="submit" name="btn-login">Log In</button>
Sign Up
</form>
</div>
</div>
<?php include "includes/footer.php"; ?>
</body>
</html>
Thank you once again for any help in advance
There's all kinds of wrong in your example. It doesn't matter where yo put your PHP code: if you want to append something to some sort of a div - then delay that until the dom loads. You'd be better off using jquery or something that had a "domReady" function available, but you can do without it as well. Instead of your document.write script you could just say:
window.onload = function() { document.getElementById('something').innerHTML = 'some html'; };
The above line would wait for the document to be loaded and it would now be able to find the div even if php code is above everything else.
It is really very easy do it in this way
PHP File:
<?php
session_start();
include_once 'dbconnect.php';
$error="no";
if(isset($_SESSION['user'])!="")
{
header("Location: account.php");
}
if(isset($_POST['btn-login']))
{
$email = mysql_real_escape_string($_POST['email']);
$upass = mysql_real_escape_string($_POST['pass']);
$res=mysql_query("SELECT * FROM users WHERE email='$email'");
$row=mysql_fetch_array($res);
if($row['password']==md5($upass))
{
$_SESSION['user'] = $row['user_id'];
header("Location: account.php");
}
else
{
$error="yes";
}
}
?>
HTML:
<?php include"authentication/login.php";?>
<!DOCTYPE html>
<html>
<HEAD>
<title>Website | Loign</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<?php include "includes/page_sources.php"; ?>
</HEAD>
<body>
<?php include "includes/navigation.php"; ?>
<div id="wrapper">
<div id="login-form">
<form method="post">
<?php if($error=="yes") echo 'Incorrect Username or Password';?>
<input type="text" name="email" placeholder="Your Email" required />
<input type="password" name="pass" placeholder="Your Password" required />
<button type="submit" name="btn-login">Log In</button>
Sign Up
</form>
</div>
</div>
<?php include "includes/footer.php"; ?>
</body>
</html>

Why aren't <script> tags not working on this PHP page?

When I try to enter
<script type="text/javascript" >
alert("hello");
</script>
in the comment box on my PHP page I do not get an alert box. I see the script in my text file, not on the webpage. For some reason the <script> isn't executing. I have active scripting and javascript enabled on all my browsers.
My PHP code:
<?php //CFPcomments.php
include_once 'CFPheader.php';
if (isset($_POST['content']))
{
$fp = fopen('comments.txt', 'a');
fwrite($fp, $_POST['content'] . "<br />");
fclose($fp);
}
echo nl2br(file_get_contents('comments.txt'));
echo <<<_END
<h3>Post comment</h3>
<form action='CFPcomments.php' method='post'>
<textarea name='content' rows ='3' cols='100'></textarea>
<br/>
<input type='submit' value='Post' />
</form>
_END;
?>
Strange. I got it to work, not sure why.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
alert("hello");
</script>
</head>
<body>
</body>
</html>
When I type this in it seems to work
Anyone have any idea why???? Very confused.
your nl2br() is most likely translating
<script type="text/javascript" >
alert("hello");
</script>
to
<script type="text/javascript" ><br/>
alert("hello");<br/>
</script><br/>
and breaking the JavaScript code.
I assigned a variable to the content, then displayed the variable in the PHP code. Now it works.
<?php //CFPcomments.php
include_once 'CFPheader.php';
setcookie("username", $GLOBALS['user'], time()+3600);
setcookie("password", $GLOBALS['pass'], time()+3600);
if (isset($_POST['content']))
{
$fp = fopen('comments.txt', 'a');
fwrite($fp, $_POST['content'] . "<br />");
fclose($fp);
}
$comment = file_get_contents('comments.txt');
echo <<<_END
<h3>Post comment</h3>
'$comment'
<form action='CFPcomments.php' method='post'>
<textarea name='content' rows ='3' cols='100'></textarea>
<br/>
<input type='submit' value='Post' />
</form>
_END;
?>

Categories