I am trying to send a PHP variable to a Javascript funtion using HTML. I dont know if it is possible or not. I am a newbie.
This is all the code in both the files, index.php and abc.php
P.S. I have changed the file name from index.html to index.php
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml-transitional.dtd">
<?php
require("../php/abc.php");
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Some Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="file.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="here.js"></script>
</head>
<body onload="init();">
<noscript>
Your browser does not support Javascript!!
</noscript>
<table id="content">
<tr>
<td>
<div id="scroll"></div>
</td>
<td id="colorpicker" valign="top">
<img src="palette.png" id="palette" alt="Color Palette" border="1" onclick="getColor(event);" />
<br />
<input id="color" type="hidden" readonly="true" value="#000000" />
<span id="sampleText">
(text will look like this)
</span>
</td>
</tr>
</table>
<div>
<input type="text" id="userName" maxlength="50" size="10" onblur="javascript: check('<?php echo $phpVariable; ?>');" />
<input type="text" id="messageBox" maxlength="2000" size="50" onkeydown="handleKey(event);" />
<input type="button" value="Send" onclick="sendMessage();" />
<input type="button" value="Delete All" onclick="deleteMessages();" />
</div>
</body>
</html>
Javscript function
function check(param_name)
{
var oUser=document.getElementById("userName");
oUser.value = param_name;
}
abc.php
if(isset($_POST['user_name'], $_POST['action'])) {
$user_name = $_POST['user_name'];
$action = $_POST['action'];
if($action == 'joined') {
$phpVariable = user_joined($user_name);
}
function user_joined($user_name) {
$servername = "";
$username = "";
$password = "";
$dbname = "";
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user_name = mysql_real_escape_string(htmlentities($user_name));
$sql = "INSERT INTO table_name (column_name) VALUES ('$user_name')";
$query = "INSERT INTO table_name2 (column_name) VALUES ('$user_name')";
$result = $conn->query($query);
if($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error in inserting: " . $sql. "<br>" . $conn->error;
}
return $user_name;
$conn->close();
}
Try something like that
HTML
<input type="text" id="nametxt" />
<button id="btn-check"></button>
Javascript
$(document).ready(function (){
$("#btn-check").click(function(){
var name = $('#nametxt').val();
var login = {
parameter: name
};
$.ajax({
type: 'POST',
url: 'file.php',
data: login,
datatype: 'json'
}).done(function(data) {
console.log(data);
});
});
});
PHP
<?php
//do some
echo information; -- this way return parameters
?>
As you have written, the way to output the value of a PHP variable to an HTML page is by doing <?php echo $phpVariable ?>. In newer versions of PHP (and in older ones where the setting was turned on), you can shorten this to <?= $phpVariable ?>.
You are getting an 'undefined variable' warning probably because the $phpVariable is not getting set. In your code, this variable is only initialized if $action == 'joined'. If you want it to have a default value, give it one first:
$phpVariable = null;
// note that three equals signs are not necessary here
// but a good habit for cases where it matters
if ($action === 'joined') { ... }
When you output the PHP variable into a JavaScript string, you should escape the output so that you don't leave your visitors vulnerable to XSS (cross-site scripting) attacks. In this case, json_encode should be sufficient. However, since your JavaScript is not within a <script> tag, but rather within an onblur attribute, you have to escape any characters which are special in HTML. Since you're using double quotes around the attribute value, htmlspecialchars is sufficient for that. So in all, you will output htmlspecialchars(json_encode($phpVariable)). The reason for all this is that you don't want to rely on your input being clean -- mistakes will be made and when they do, you don't want to let someone attack your users.
<input type="text" id="userName" maxlength="50" size="10"
onblur="javascript: check('<?= htmlspecialchars(json_encode($phpVariable)) ?>');" />
Since we've given a default value (null) for $phpVariable and we are calling the check function with it, we should add a "check" to the check function to ensure that we got a real value, like this:
// you should use camelCase or under_scores, but not both, for consistency
function check(paramName) {
// loose equals to match null or undefined
if (paramName == null) {
return;
}
var oUser = document.getElementById("userName");
oUser.value = paramName;
}
Alternatively, if you want to be really careful about your function inputs, you could verify that paramName is a string and that it has a nonzero length, but in a dynamically typed language like JavaScript, doing all these checks manually sometimes becomes a losing battle.
This is not going to work as-is because PHP is executed server-side and JavaScript is executed client-side.
In order to do this, you're going to have to make an AJAX call to a PHP file and then use JavaScript on the results.
Related
I have this code:
<!DOCTYPE html>
<html>
<head>
<title>Sign up page</title>
<meta charset="UTF-8"/>
</head>
<body>
<h1>Sign up page</h1>
<form action="test.php" method="post">
<input placeholder="Enter your username" name="username"/><br/>
<input type="password" placeholder="Enter your password" style="margin-bottom:5px" name="password"/><br/>
<button type="submit" name="submit">Sign up</button>
</form>
<?php
if(isset($_POST["username"],$_POST["password"],$_POST["submit"])){
if(mb_strlen($_POST["username"])<8){
?>
<script>
alert("Your username must be at least 8 characters long.");
var i=document.getElementsByTagName("input")[0];
i.value="<?php echo $_POST['username']; ?>";
i.focus();
</script>
<?php
}else if(mb_strlen($_POST["password"])<8){
?>
<script>
alert("Your password must be at least 8 characters long.");
var i=document.getElementsByTagName("input")[1];
i.value="<?php echo $_POST['password']; ?>";
i.focus();
</script>
<?php
}else{
echo "Successfully signed up!";
}
}
?>
</body>
</html>
It works fine most of the time, but if you try entering ";f(); into the username field, you get an error in the console and no alert.
As is clearly visible, that is happening because when PHP receives the input, it echoes it in the JS string. "; ends the string and the statement, while f(); causes an error which prevents the input from focusing. This occurred under 8 characters, therefore causing it to fall under mb_strlen($_POST["username"])<8.
Usually I would just use htmlspecialchars, but if you try adding that, then if you put ";<!--, it comes out with < instead of <. Some users may want < (or other &*; characters) in their username, and (if they weren't developers) would be surprised what < means.
So how do I prevent the JavaScript Injection from occurring while still keeping User Friendliness?
You should be using json_encode to output your values (and note you no longer need the enclosing "s):
i.value=<?php echo json_encode($_POST['username']); ?>;
This will ensure that quotes within the string are escaped and the entire value is treated by JavaScript as a string. For your example data, this will produce
"\";f();"
The problem is the double-quote in this example. Try addslashes:
i.value="<?php echo addslashes($_POST['username']); ?>";
Though Nick's answer may be better for JS. I'm more PHP than JS.
You should never inject unsanitized code into anything. This can cause XSS attacks at the least.
I think the easiest way to sanitize your code while keeping the user friendliness would be to use json_encode()
<?php
}else if(mb_strlen($_POST["password"])<8){
$data = json_encode(['password' => $_POST['password']]);
?>
<script>
alert("Your password must be at least 8 characters long.");
var user_data = <?php echo $data; ?>;
var i=document.getElementsByTagName("input")[1];
i.value=user_data.password;
i.focus();
</script>
However!
You should really be putting this in the Input element:
<input type="password" value="<?=htmlspecialchars($_POST['password'] ?? '',ENT_QUOTES); ?>" placeholder="Enter your password" style="margin-bottom:5px" name="password"/>
This question already has answers here:
How to get input field value using PHP
(7 answers)
Closed 6 years ago.
I am writing basic user register page,
My register page contain : usermail ,password, plan type.
There are three plans for plan type.
Three plans are: basic, sliver and gold.
The register_main.php is to store user information in Mysql.
I met issue that is when I click basic or sliver or gold plan, the page will go to register_main page .
I want sent user information only to server ,when they click sign in.
Can anyone help me to solve this issue?
HTML Code:
<html>
<head>
<title>Register</title>
<meta charset="UTF-8">
<!-- Include JS File Here -->
<script src="Script/register_validate.js">
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
</script>
</head>
<body>
<form name="registerform" action="register_main.php" method="post" onsubmit="return validate()">
<p id="benefits_text" class="white size_8">Benefits:</p>
<input id="type_basic" type ="image" name="basicPlan" " src="basic.png">
<input id="type_silver" type ="image" name="silverPlan" " src="silver.png">
<input id="type_gold" type ="image" name="goldPlan" " src="gold.png">
<div id="userinfo_content">
<p id="email_text" class="white size_8">Email Address</p>
<input id="email_input" name="userEmail" type="text"class="sign_input">
<p id="password_text" class="white size_8">Password</p>
<input id="password_input" name="password" type="password">
<p id="confirmPW_text" class="white size_8">Confirm Password</p>
<input id="confirmPW_input" name="confirm_password" type="password">
<input id="btn_signin" type ="image" alt ="submit" src="signin.png">
</div>
</form></body>
</html>
register_main.php
include ("config.php");
require ("encrypt.php");
session_start ();
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
// Get userEmail from client side and create a legal SQL string that you can use in an SQL statement.
$user_emailaddress = mysqli_real_escape_string ( $db, $_POST ['userEmail'] );
// Get password from client side and create a legal SQL string that you can use in an SQL statement.
$user_password = mysqli_real_escape_string ( $db, $_POST ['password'] );
// Get planType from client side and create a legal SQL string that you can use in an SQL statement.
$user_planType = mysqli_real_escape_string ( $db, $_POST ['planType'] );
// Create user.
// Note user Id is generated when a new record is inserted into a table.
$sql = "INSERT INTO admin (emailAddress,passcode,planType) VALUES ('$user_emailaddress','$user_Newpassword','$user_planType')";
$result = mysqli_query ( $db, $sql );
// if create user a successfully, jump to welcome page.
// otherwise print error information
if ($result ) {
echo "New record created successfully";
$_SESSION ['login_user'] = $user_emailaddress;
header ( "location: welcome.php" );
} else {
echo "Error: " . $sql . "<br>" . mysqli_error ( $db );
}
// Close Database
mysqli_close ( $db );
}
?>
the problem with your form is that the input tag with type="image" acts as a submit button when clicked. Check out this link: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/image.
I guess that in your use case, you want these images to act as selection buttons for the available plan types. So I think you could replace then for an image tag with a radio button, or a select input with the three plans.
everybody.
I have the following situation:
I have:
http://example.com/ and http://example.com/new
In example.com, I have some forms that I load in example.com/new domain with fancybox iframe.
My form, basically shows some fields for the user to enter his pessoal data, like name, phone and etc... After he submit that, I show some user agreement terms that comes from database and a checkbox for the user to say that he agree with the terms.
After he check and submit, I want to alert some sucess message and the fancybox modal/iframe to close and thats it.
In the form page, i've loaded jquery, and bootstrap. So, when the user agree, I print:
<?php
echo "
<script>
alert('Some success message!');
$(document).ready(function(){
parent.$.fancybox.close();
});
</script>
";
?>
I have three forms, in one, works, in the other two, i get:
Error: Permission denied to access property '$'
The only difference between the form that works and the other two, is that in the form that works, i don't have the agreement terms coming from database, only the checkbox.
I could put my entire code here, but would be a giant question. But if you guys need, I can update.
Sorry for my english and forgive-me if I was not clear.
UPDATE:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<?php
/* Connect with DB */
require_once('require/conectar.php');
if(!empty($_POST))
foreach($_POST as $k => $v)
$$k = $v;
?>
<script type="text/javascript" src="http://example.com/new/assets/js/jquery.js"></script>
</head>
<body>
<?php if(!isset($agree) and !isset($next)): ?>
<h1>The form</h1>
<form method="post" action="">
<label>Your name:</label>
<input type="text" name="name">
<br>
<label>Your email:</label>
<input type="text" name="email">
<br>
<input type="submit" name="next">
</form>
<?php
else:
$error = (!isset($name)) ? true : false;
$error = (!isset($name)) ? true : false;
if($error)
{
echo '<script>You must fill all fields before submit.</script>';
exit;
}
$qrr = mysql_query("SELECT * FROM `terms`");
$terms = mysql_fetch_object($qrr);
?>
<h1>Terms:</h1>
<?php echo $terms->content; ?>
<form method="post" action="">
<input type="hidden" value="<?php echo $name; ?>" name="name">
<input type="hidden" value="<?php echo $email; ?>" name="email">
<input type="checkbox" value="1" name="accept"> I agree.
<input type="submit" name="agree">
</form>
<?php
endif;
if(isset($agree))
{
/*
Here i mail me the user data.
*/
echo "
<script>
alert('Soliciação Realizada com sucesso!');
$(document).ready(function(){
parent.$.fancybox.close();
});
</script>
";
}else
{
echo "<script>alert('You need to agree with the terms to proceed.');</script>";
}
?>
</body>
</html>
This is a browser security thing. While there's a few ways around it, the best one is probably to use the postMessage API.
On your example.com parent page, add some code like this:
function handleMessageFromiFrame(event) {
alert('Some success message: ' + event.data);
//$.fancybox.close();
}
window.addEventListener("message", handleMessageFromiFrame, false);
And, then on your child example.com/new iframe, add code like this:
var parentOrigin = "*"; // set to http://example.com/ or whatever for added security.
function sendMessageToParent(){
parent.postMessage("button clicked", parentOrigin);
}
$('#submit-btn').click(sendMessageToParent);
Here's an example of it in action:
Parent example.com page: http://jsbin.com/hiqoyevici/1/edit?html,js,output
Child example.com/new iframe: http://jsbin.com/goferunudo/1/edit?html,js,output
When you click the button in the child page, it uses postMessage to notify the parent. Then the parent listens for the message and does whatever action you want.
I am trying to make a basic login screen using Javascript, in which I don't have much experience. I managed to get this much, but for some reason, whenever I enter text into the input box it will redirect me, no matter whether it is the correct password or not.
Also, a second question, to determine whether or not a user has logged in (to redirect them to the login page), would I have to use something other than JS, such as PHP?
Code:
<!doctype html>
<html>
<head>
<title>Login</title>
<script type="text/javascript">
function login()
{
if (password = "cat")
{
location.assign("home.html");
}
}
</script>
</head>
<body>
Password: <input type = "password" name = "password">
<input type = "button" value = "Login" onclick = "login()">
</body>
</html>
currently you are using if(password = "cat") which is actually an assignment operator not used for comparison. If you don't know the type of data to be compared use == otherwise you can use ===.
In otherword
== is used to compare the values only.
=== is used to compare the values as well as type.
Check like this
if(password === "cat")
And for your another query if you want to make a web app or something. You should use server side interaction using PHP or WPF or any other like JSON etc.
This question has been asked by many before. The code needs to use an Ajax request to the server.
Also , you do need a server side language to do the validation . Something like below, example is using Jquery library
HTML
<body>
<?php session_start(); ?>
<div id="profile">
<?php if(isset($_SESSION['user_name'])){
?>
<a href='logout.php' id='logout'>Logout</a>
<?php }else {?>
<a id="login_a" href="#">login</a>
<?php } ?>
</div>
<div id="login_form">
<div class="err" id="add_err"></div>
<form action="login.php">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name" />
<label>Password:</label>
<input type="password" id="password" name="password" />
<label></label><br/>
<input type="submit" id="login" value="Login" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
</div>
<div id="shadow" class="popup"></div>
</body>
Javascript
<script type="text/javascript">
$(document).ready(function(){
$("#login_a").click(function(){
$("#shadow").fadeIn("normal");
$("#login_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function(){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function(){
username=$("#user_name").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true')
{
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
}
else
{
$("#add_err").html("Wrong username or password");
}
},
beforeSend:function()
{
$("#add_err").html("Loading...")
}
});
return false;
});
});
</script>
PHP code
<?php
session_start();
$username = $_POST['name'];
$password = md5($_POST['pwd']);
$mysqli=mysqli_connect('localhost','username','password','database');
$query = "SELECT * FROM user WHERE username='$username' AND password='$password'";
$result = mysqli_query($mysqli,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row >=1 ) {
echo 'true';
$_SESSION['user_name']=$row['username'];
}
else{
echo 'false';
}
?>
This is really the wrong way to implement login. Any password checking has to happen on the server, because otherwise the password will be visible on the client, and it will be trivial for users to see the required password. Furthermore, please, please, please, please do not create yet another username/password login... this is what OAuth2 is intended to solve; let the identity experts handle login, and simply delegate to another identity provider.
That being said, the error in your code is that you use a single equals sign ("=") which performs assignment, whereas you really intend to use the double equals ("==") or triple equals ("===") for comparison.
I am a learning Javascript and PHP, I am trying to do this ,
I have stored some variables in a PHP session, i am trying to set the values present in the session as the values in the form's input field, i have used javascript for that purpose,
PHP :
<html>
<head>
<link rel='stylesheet' type='text/css' href='http://localhost/Matrix/frameCSS.css' />
<script lang='text/javascript' src='http://localhost/Matrix/gd.js'></script>
</head>
<body>
<?php
// ------- --------- -------- -------- ------
$debug=true;
dBug("Started Code Execution ... ");
function dBug($text)
{
global $debug;
if($debug) { echo "<p class='status'>debug : $text</p>"; }
else { return; }
}
// ------ ----------- ------------ -----------
$db = mysqli_connect("127.0.0.1","user","xyz","sample");
if(mysqli_connect_errno())
{
die(mysqli_connect_error());
}
session_start();
if($_SESSION['is_open']==true)
{
$username = $_SESSION['username'];
dBug('retreived username > '.$username);
}
?>
<table class="content">
<form method="POST" action="http://localhost/gen_det.php" onload="load_data()">
<tr>
<td>
Full Name :
</td>
<td>
<input type="text" class="txtbox" id='name'/>
</td>
</tr>
<tr>
<td>
Age :
</td>
<td>
<input type="text" class="txtbox" id='age' />
</td>
</tr>
<tr>
<td>
<p class='status' id='status'> </p>
</td>
</tr>
<tr>
<td colspan="2" align='center'>
<input type="submit" class="btn" onclick="return validateData();" value="save" />
<input type="button" class="btn" onclick="redirect()" value="cancel" />
</td>
</tr>
</form>
</table>
</body>
Javascript :
function load_data()
{
var name = document.getElementById('name');
var age = document.getElementById('age');
name.value = " <?php echo ''.$_SESSION['username']; ?> ";
age.value = " <?php echo ''.$_SESSION['username']; ?> ";
}
This page is actually inside a iframe in another page (if that is important). When I open this page, it opens , but the values aren't filled in the text fields. What have I done wrong ?
here is the method
<body onload="javascript: load_data('<?php echo $_SESSION['name']; ?>', '<?php echo $_SESSION['age']; ?>') >
and in the JS file you can define the function
function load_data(param_name, param_age)
{
var name = document.getElementById('name');
var age = document.getElementById('age');
name.value = param_name;
age.value = param_age;
}
Your <form> tag cannot have an onload attribute. This is simply not possible.
Try assigning the onload event to your <body> element:
<body onload="load_data();">
A better solution would be to directly register the event in the JavaScript code:
window.addEventListener("load", load_data);
For one, you're inserting your PHP data incorrectly. You can very easily produce JS syntax errors by directly dumping arbitrary PHP values into a JS context. You should ALWAYS use json_encode() to produce valid JS text:
name.value = <?php echo json_encode($_SESSION'username']); ?>;
json encoding will take care of any quoting/escaping necessary.
You don't mention HOW this JS is getting included in your site. If it's in (say) an external .js file, then by default this file will NOT be passed through the PHP interpreter, and you'll be sending raw un-executed PHP code to the browser, where it will be seen by the JS parser and rejected as a outright syntax error. That will kill the entire script block and your JS code dies right then and there.
If it is somehow being parsed/executed by the server, then you should directly hit that JS script file with your browser and see WHAT is being output. There could be other structural problems causing JS to ignore the entire script.
If you already have the value of the data within the PHP variable you can just build the required input element with the value already included
<input type="hidden" id="foo" name="foo" value="<?php echo $_SESSION['foo']; ?>"/>
When your event (click/submit) fires the target element will then contain the value
foo = document.getElementById('foo');
console.log(foo.value);
well is very simple, when a web page is loaded the load order they are as follows.
HTML->CSS->JavaScript->PHP.
So if you want to get that variable in your js file, you have to do it this way...
<html>
<head>
<link rel='stylesheet' type='text/css' href='http://localhost/Matrix/frameCSS.css' />
<script lang='text/javascript' src='http://localhost/Matrix/gd.js'></script>
<script>
function load_data()
{
var name = document.getElementById('name');
var age = document.getElementById('age');
name.value = "<?php echo ''.$_SESSION['username']; ?>";
age.value = "<?php echo ''.$_SESSION['username']; ?>";
}
</script>
</head>
<body>
...
</body>
</html>