Embedded JavaScript in PHP can not manipulate DOM in HTML - javascript

I have a PHP to verify the HTML form (post method). If the value doesn't match, the error message should be added at the HTML page. I test the embedded JS script in console, it works. But it doesn't work in PHP. How can I fix it? Thank you
Here is my code
<!DOCTYPE html>
<body>
<form action="http://localhost/submitTest.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<div id="submitField">
<input type="submit">
</div>
</form>
</body>
</html>
<?php
if ($_GET["name"] == 1 && $_GET["email"] == 2) {
header('Location: http://localhost/table.html');
} else {
$url = 'http://localhost/submitTest.html';
echo "<meta http-equiv='Refresh' content='0;URL=$url'>";
echo "
<script>
var messageP = document.createElement('span');
messageP.style.color = 'red';
var parent = document.getElementById('submitField');
parent.appendChild(messageP);
messageP.innerHTML = 'not match';
</script>";
}
?>
I want to do something like thiserror message

Related

Redirect to HTML input value from PHP

So I want to create a simple result page that lets users download their results using the given code.
This is the script:
<form action="" method="post" >
<input type="text" name="logincode">
<input type="submit" name="send">
</form>
<?php
$name = $_POST['logincode'];
$filename = $name.'/'.$name.'pdf';
header('Location: ./'$filename'');
?>
The principle is when the user writes into the input field, for example (1234) and hits enter, it should redirect him to:
./1234/1234.pdf
I don't know where the mistake is in my code.
Few issues,
Your header should be before anything else as #showdev mentioned in a comment.
You're missing a . between filename and extension
You also have a syntax error in the header trailing ''
And you should exit redirect headers.
You should also be checking your variables as you go, plus check the file exists, so you can show errors.
<?php
// check post request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$errors = [];
// check logincode is set and a number
if (!isset($_POST['logincode']) || !is_numeric($_POST['logincode'])) {
$errors['logincode'] = 'Invalid login code';
} else {
$name = $_POST['logincode'];
// check file is found
if (!file_exists($name.'/'.$name.'.pdf')) {
$errors['logincode'] = 'Your results are not ready.';
}
// now check for empty errors
if (empty($errors)) {
exit(header('Location: ./'.$name.'/'.$name.'.pdf'));
}
}
}
?>
<form action="" method="post">
<?= (!empty($errors['logincode']) ? $errors['logincode'] : '') ?>
<input type="text" name="logincode">
<input type="submit" name="send">
</form>
You are missing a “.” before pdf aren’t you?
And also wrong header('Location: ./'$filename'');
Try this :)
<?php
$name = $_POST['logincode'];
$filename = $name.'/'.$name.'.pdf';
header('Location: ./'.$filename);
?>
It's very insecure code!
Major changes below:
write test for user input data TODO by you
change order PHP block code first, form (HTML) code next in snippet
add test is post request_method before any $_POST['...']; in snippet
add .(dot) before filename extension i $filename in snippet
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $_POST['logincode'];
$filename = $name.'/'.$name.'.pdf';
header('Location: ./'$filename'');
}
?>
<form action="" method="post" >
<input type="text" name="logincode">
<input type="submit" name="send">
</form>
<form action="" method="post" >
<input type="text" name="logincode">
<input type="submit" name="send">
</form>
<?php
if($_POST){
$name = $_POST['logincode'];
$filename = $name.'/'.$name.'.pdf';
header('Location: ./'.$filename.'');
}
?>

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>

function is executed without being called [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
My code is supposed to store the info that the user inserts and store it in a Database.
This function should be called on a button click, but the problem is that the function runs when the page loads and when I press the button.
here is my code
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<?php
function write_command($name,$address,$telephone,$cart){
$servername = 'localhost';
$server_username = 'root';
$server_password = '';
$DB_name = 'OnlineGarcon';
$DB_connect = mysqli_connect($servername,$server_username,$server_password,$DB_name);
if ($DB_connect -> connect_error){
echo 'unable to connect to due to server error!';
}else{
$_write_command = "INSERT INTO `orders`(`name`, `address`, `telephone`, `cart`) VALUES ('$name','$address','$telephone','$cart')";
if ($DB_connect->query($_write_command) == TRUE) {
echo "Order was placed,Thanks!\nyour order was:$cart";
} else {
echo "Server error!";
}
}
}
?>
<center>
<form method="POST">
<input name="name" class="field" placeholder="Full name"></input>
<br>
<br>
<input name="address" class="field" placeholder="Address"></input>
</br>
</br>
<input name="telephone" class="field" placeholder="Telephone/Mobile number"></input>
<br>
<br>
<br>
<br>
<button id="submit">Submit order</button>
</br>
</br>
</br>
</br>
</form>
<script>
$("#submit").click(function(){
alert('<?php
$name = $_POST['name'];
$address = $_POST['address'];
$telephone = $_POST['telephone'];
$cart = $_GET['cart'];
write_command($name,$address,$telephone,$cart);
?>');
});
</script>
</body>
</html>
Using an jQuery Ajax call you you can do this quite simply.
form.php
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<input name="name" id="name" placeholder="Full name">
<input name="address" name="address" placeholder="Address">
<input name="telephone" id="telephone" placeholder="Telephone/Mobile number">
<button id="submit">Submit order</button>
<script type="text/javascript">
$('#submit').click( function() {
$.ajax({
url: "functions.php",
type: "POST",
data: {
name: $('#name').val();
address: $('#address').val();
telephone: $('#telephone').val();
cart: <?php echo $_GET['cart']; ?>
}
});
});
</script>
</body>
</html>
functions.php
<?php
function write_command($name, $address, $telephone, $cart) {
$servername = 'localhost';
$server_username = 'root';
$server_password = '';
$DB_name = 'OnlineGarcon';
$DB_connect = mysqli_connect($servername,$server_username,$server_password,$DB_name);
if( $DB_connect->connect_error ){
echo 'unable to connect to due to server error!';
} else {
$_write_command = "INSERT INTO `orders`(`name`, `address`, `telephone`, `cart`) VALUES ('$name','$address','$telephone','$cart')";
if ($DB_connect->query($_write_command) == TRUE) {
echo "Order was placed,Thanks!\nyour order was:$cart";
} else {
echo "Server error!";
}
}
}
write_command( $_POST['name'], $_POST['address'], $_POST['telephone'], $_POST['cart'] );
This will happen , what you need to do is
Method 1: <form method="POST" onsubmit="callFuntion()">
Method 2:
<form action="demo_form.php" method="post">
put all your php code in file demo_form.php and when the submit is clicked it will go that file , which will help you to call the
function once not twice .

save data from php to ajax and change color of div when new data insert?

Hi i am trying to save value and alert them using ajax which i am insert using php in my sql table but my alert is not working
Here is my code
demo.php
<html>
<head>
<script>
function my(){
var name = document.getElementById("name").value;
var last_name = document.getElementById("last_name").value;
document.getElementsById('div1').style.backgroundColor = green;
var dataString = 'name='+name+'&last_name='+last_name;
$.ajax({
type:'POST',
data:dataString,
url:'demo.php',
success:function(data) {
alert(data);
}
});
} </script>
</head>
<body>
<form action="" method="post">
<input type="text" name="name" id="name" value="" />
<input type="text" name="last_name" id="last_name" value="" />
<input type="submit" name="Update" id="update" value="Update" onclick="my();" />
</form>
<div id="div1" style="width:300px;height: 50px;background-color: yellow;" >
</div>
</body>
</html>
<?php
include('conn.php');
if (isset($_POST['Update'])) {
$name = $_POST['name'];
$last_name = $_POST['last_name'];
echo $name;
$insert = "insert into ajaxsave values('$name','$last_name')";// Do Your Insert Query
if(mysql_query($insert)) {
echo "Success";
} else {
echo "Cannot Insert";
}
}?>
demo.html
<html>
<head>
</head>
<body>
<div id="div2" style="width:300px;height: 50px;background-color: yellow;" >
</div>
</body>
</html>
here i want when i submit form them div color should change which is in demo.html
where i am wrong in this code
and how can i achieve my goal
Any help will be appreciated
changes you need to make:
add jquery as a dependency as you are using $.ajax utility function which is provided by Jquery.
As you are using Jquery, you could use its selectors for getting values of elements and binding functions to dom elements. I have commented it in the source code.
You are using a form with a submit button and executing the ajax call on click of it. But you need to prevent the page from submitting the form by preventing the default behavior of the submit button. Refer event.preventDefault();
Move the php ajax response part to the top and call exit() once your response is complete. Else your ajax response will include the whole page html source also.
.
<?php
include('conn.php');
if (isset($_POST['Update'])) {
$name = $_POST['name'];
$last_name = $_POST['last_name'];
$insert = "insert into ajaxsave values('$name','$last_name')";// Do Your Insert Query
if(mysql_query($insert)) {
echo "Success";
} else {
echo "Cannot Insert";
}
//Call exit as your ajax response ends here. You dont need the html source along with it.
exit();
}
?>
<html>
<head>
</head>
<body>
<form action="" method="post">
<input type="text" name="name" id="name" value="" />
<input type="text" name="last_name" id="last_name" value="" />
<input type="submit" name="Update" id="update" value="Update" />
</form>
<div id="div1" style="width:300px;height: 50px;background-color: yellow;" >
</div>
<!-- include jquery dependeny before your js code block -->
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script>
$("#update").on("click",function(event) {
//Prevent Default submit button behavour. Prevent the form from submission.
event.preventDefault();
// using Jquery selectors for better readability of code.
var name = $("#name").val();
var last_name = $("#last_name").val();
$("#last_name").css("background-color","green");
$.ajax({
type:'POST',
data:{name:name,last_name:last_name,Update:true},
url:'demo.php',
success:function(data) {
alert(data);
}
});
});
</script>
</body>
</html>
You send two parameters in "dataString" variable, and then in php check undefined variable "Update"
So, just replace string
if (isset($_POST['Update'])) {
to
if (isset($_POST['name']) && isset($_POST['name'])) {
And add this line to tag
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

Values to PHP function parameters from Button click Javascript function

Friends,
I'm a newbie to PHP.
I've had a problem to deal with that I couldn't understand, so I posted it in this thread.
I've dynamically created 2 textboxes and a button.
Question ID text field
Question text field
Change Button
for the change button I need to write a 'onclick' javascript to pass Question ID
and Question value to a PHP function (set_id) written inside the Same file. In fact that’s why i
Called Form action $_SERVER[“PHP_SELF”].
Here’s my code.
<html>
<head>
<script>
function getvalue(value)
{
var qid_value = 'qid_'+value.substring(4);
alert('QID = '+ document.getElementById(qid_value).value + ' QUESTION = ' + document.getElementById(value.substring(4)).value);
/*
I created this javascript alert to test the id s of textboxes and their values
*/
}
</script>
</head>
<body>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<!-- These fields are dynamically created -->
<input type="text" id="'.$var_id.'" name="'.$var_id.'" value="'.$row['qid'].'" readonly size="2 px"/>
<input type="text" id="'.$var_question.'" name="'.$var_question.'" value="'.$row['question'].'" style="size:auto"/>
<input type="button" id="'.$var_question.'" name="'.$var_question.'" value="Change" onclick="getvalue(this.name)"/>
<!-- These fields are dynamically created -->
</form>
</body>
</html>
<?php
$msg= "";
function display($qid,$question)
{
require('uni_db_conn.php'); // this is my db connection
$qid = $_POST[$qid];
$question= $_POST[$question];
$query = "UPDATE question SET question='.$question.' WHERE qid='.$qid.'";
$result = mysql_query($query);
if(!$result)
{
$msg= 'Cant Insert Values to the Table !'.mysql_error();
}
else
{
$msg = 'Successfully Added to the Table !';
}
echo '<label>'.$msg.'</label>';
}
function set_id($qid,$question)
{
if(isset($_POST[$question]))
{
display($qid,$question);
}
}
?>
Thank You ! Sorry If there was any mistake.
Try this code
<?php
if(isset($_POST['submit'])){
$QID = $_POST["qid"];
$QUE = $_POST["question"];
echo $QID;
echo $QUE;
}
?>
<html>
<head>
<script language="javascript">
function getvalue()
{
var valid= true;
var id = document.getElementById("ID").value;
var ques = document.getElementById("ques").value;
return valid;
}
</script>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onSubmit=" return getvalue()" >
<input type="text" id="ID" name="qid"/>
<input type="text" id="ques" name="question"/>
<input type="submit" name="submit" value="Change"/>
</form>
</body>
</html>

Categories