passing variable from php to javascript - javascript

I want to know why the variable user won't work.
<script type="text/javascript">
var user = <?php echo $r;?>;
document.write(user);
</script>
<form method="post" action="<?PHP echo $_SERVER["PHP_SELF"]?>">
<input type="text" name="username" placeholder="username"><br><br>
<input type="password" name="pw" placeholder="password"><br>
<input type="submit" value="UPDATE" ="loadXMLDoc()">
</form>

Assuming $r is a string, you need to wrap it in quotes:
var user = '<?php echo $r;?>';
Without the quotes, the browser is seeing:
var user = Sandeep;
Better still, use PHP to JSON encode the string, which will escape any quotes and prevent an XSS vulnerability:
var user = <?php echo json_encode($r);?>;
Side note, echoing $_SERVER["PHP_SELF"] into HTML is known XSS vulnerability. You should run it through htmlspecialchars():
<form method="post" action="<?PHP echo htmlspecialchars($_SERVER["PHP_SELF"])?>">

Related

passing php variable as function argument

I have home.php and I am trying to pass two php variables in an onclick() function. But it does not work. I am new in php so any suggestion will be very helpful.
<form action="process/home.php" method="post">
<input type="text" name="userfrom" value="<?php echo htmlspecialchars($username); ?>"/>
<input type="submit" onclick=show('$user_id','$_SESSION['id']') value="Add Friend"/>
</form>
In the show() function I wanted to store the values in the database.
function show($userfrom,$userto){
$sql="INSERT INTO user (userfrom,userto) VALUES ('$userfrom','$userto')";
mysql_query($sql);
<!--it is not working-->
}
Your are new in php. So, remember this, you can't use PHP functions in JS code. onClick event needs js function. So firstly, you should pass your variables, with form then get it and after that you can use php functions.
You can use this code, but not recommended
<form action="" method="post">
<input type="text" name="userfrom" value="<?= htmlspecialchars($username); ?>"/>
<input type="submit" name="addFriend" />
</form>
<?php
if (isset($_POST['addFriend'])) {
show($user_id, $_SESSION['id']);
}
?>
You should learn about jquery ajax. (Advice for you)
Try below code, You have some syntax errors,
<form action="process/home.php" method="post">
<input type="text" name="userfrom" value="<?php echo htmlspecialchars($username); ?>"/>
<input type="submit" onclick="show(<?php echo $userid ; ?>, <?php echo
$_SESSION['id']; ?>)" value="Add Friend"/>
</form>
You need to echo your php variables into HTML elements.
onclick=show('<?=$user_id;?>','<?=$_SESSION['id'];?>')
shorthand for echo: <?=
and don't forget to add quotations when passing string values.

How to add value="" to input

Is there a possibility to add the value tag to an input with javascript?
e.g. to change a input fild in a form from:
<input type="text" name="mail" id="mail">
to:
<input type="text" name="mail" id="mail" value="<?php echo $_SESSION['email'] ?>
EDIT:
<?php
echo '
<script type="text/javascript">
document.getElementById("mail").setAttribute("value", "<?php echo $_SESSION["email"];?>");
</script>';
?>
Use setAttribute() to fill in the attribute of an element.
document.getElementById("mail").setAttribute("value", "<?php echo $_SESSION['email'];?>");
<input type="text" name="mail" id="mail">
You can't use <?php inside a PHP string. Use concatenation instead.
<?php
echo '
<script type="text/javascript">
document.getElementById("mail").setAttribute("value", "' . $_SESSION["email"] . '");
</script>';
?>
Yes, you can access the value field of an input with javascript
document.getElementById('mail').value = "someemail#email.com";
Not sure what you are trying to achieve but you could save PHP value as a JS variable and go from there. Something like this?
var email = '<?php echo $_SESSION['email'];?>';
document.getElementById('mail').value = email;
Using the method echo, returning the element input.
$youvalue = "This is the value of the input"
echo '<input type="text" name="mail" id="mail" value="'.$yourvalue.'">';
Using the method echo again, returning a script.
$youvalue = "This is the value of the input"
echo '<script>var x = document.createElement("input");x.type = "text";x.name = "mail";x.id = "mail";x.value = "'.$youvalue.'"; document.body.appendChild(x);</script>'

Form to edit simple website template not working

I have only used software like Adobe Muse in the past so I am quite new to coding, but I think I have the basics down.
I am trying to create a form that will alter the content on a template site that will be duplicated.
I created the form:
<form class="pure-form" id="Builder" method="POST" action="scripts\build.php">
<fieldset class="pure-group">
<input type="text" class="pure-input-1" placeholder="Store Name" name="Name">
<textarea class="pure-input-1" placeholder="Description" name="Description"></textarea>
<textarea class="pure-input-1" placeholder="About Paragraph" name="About"></textarea>
<input type="text" class="pure-input-1" placeholder="Store Address" name="Address">
<input type="text" class="pure-input-1" placeholder="Contact Number" name="Number">
<input type="text" class="pure-input-1" placeholder="Email Address" name="Email">
<input type="text" class="pure-input-1" placeholder="Tumblr Username" name="username">
<input type="text" class="pure-input-1" placeholder="Unique ID" name="unique">
<button name="btnbuild" type="submit" class="pure-button pure-input-1 pure-button-primary">Create Website</button>
</fieldset>
The form seems to be functioning alright.
I created a PHP file to get the data from this form:
<?php
$name = $_POST["Name"];
$descrip = $_POST["Description"];
$about = $_POST["About"];
$address = $_POST["Address"];
$number = $_POST["Number"];
$email = $_POST["Email"];
$username = $_POST["Username"];
$unique = $_POST["Unique"];
?>
I am not sure about the code for the images, but the variables should work alright.
In my index.html I used the following method to find and replace the strings that need to be replaced on the page.
<head>
<script>
window.onload = function() {
<?php include 'build.php'; ?>;
document.body.innerHTML = document.body.innerHTML.replace("EHNAME", "<?php echo $name; ?>");
document.body.innerHTML = document.body.innerHTML.replace("EHDESCRIPTION", "<?php echo $descrip; ?>");
document.body.innerHTML = document.body.innerHTML.replace("EHABOUT", "<?php echo $about; ?>");
document.body.innerHTML = document.body.innerHTML.replace("EHADDRESS", "<?php echo $address; ?>");
document.body.innerHTML = document.body.innerHTML.replace("EHNUMBER", "<?php echo $number; ?>");
document.body.innerHTML = document.body.innerHTML.replace("EHEMAIL", "<?php echo $email; ?>");
document.body.innerHTML = document.body.innerHTML.replace("EHUNIQUEID", "<?php echo $unique; ?>");
document.body.innerHTML = document.body.innerHTML.replace("EHUSERNAME", "<?php echo $username; ?>");
document.title = name; }
</script>
</head>
The problem is that it doesn't update the strings at all.
Any help to figure this out would be appreciated.
If I got it right, your initial form post the data to: scripts\build.php and later you are trying to get this data in another page index.html, this seems to be to problem.
Even if you import the build.php in the index.html file, this is another request, so the posted data to the build is already gone. You can solve this problem making the post directly to the index or persisting the data (in the session, for example, or database) and retrieving it in the index.html file.

Trying to validate a form client and server side

The client side validation looks something like this:
function validateFname() {
var x = document.getElementById('fname').value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
The server side below it:
if(isset($_POST['SubmitForm'])){
if(empty($_POST['fname'])){
echo "First name cannot be empty!<br/><br/>";
return false;
}
and the form itself below that:
<form name = 'checkout' method='post' action="<?php echo $_SERVER['PHP_SELF']; ?>"
accept-charset='UTF-8'>
First Name:<input type="text" name="fname" id="fname" onsubmit="return validateFname()"
class="required" value="<?php echo $fname;?>" />
<input type="submit" name="SubmitForm" value="Send"/>
Ofcourse there is a lot more to it but ive just given one example above. I am trying to figure out why the (clientside)javascript function is not working and instead the (server) php error is coming up. I need to be able to have the client run validation checks before the server to reduce load.
The onsubmit is a event that belongs to the <form> element. You have placed it with the submit button which won't work.
Here's a working fiddle:
Demo
Reference
<form name = 'checkout' method='post' action="<?php echo $_SERVER['PHP_SELF']; ?>" accept-charset='UTF-8'>
First Name:<input type="text" name="fname" id="fname" value="<?php echo $fname;?>" />
<input type="submit" name="SubmitForm" onClick="return validateFname()" value="Send"/>
</form>
try the above code. Instead of using onSubmit in input text field use onClick in submit button.
good luck

Multiple forms onclick event only working for first form

I'm sure this has been asked befor but I can't seem to find it in a search
I have multiple forms on a page generated by php all with onCick event
The problem is it only picks up the first event after that any other clicks produce same result from first click
Here is javascript
function CompareScores(form)
{
var scoreA = document.getElementById("score_A").value;
var scoreB = document.getElementById("score_B").value;
if(scoreA > scoreB){
alert('Score A is Larger ' + scoreA)
}else{
alert('Score B is Larger ' + scoreB)
}
}
And the php generating forms
<?php
while($i<=$numPrelimTeams) {
if($i!=$e) {
?>
<form action="processScores.php" method="post"><p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_A" name="score_A" size="1"></u></p>
<input type="hidden" name="team_A" value="<?php echo $prelimTeam[$i]; ?>">
<input type="hidden" name="game" value="<?php echo $game_num; ?>">
<p class="right">Game # <?php echo $game_num; ?> ) <input type="button" value="Enter Scores" onClick="CompareScores(this.form)"></p>
<?php
}else{
?>
<p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_B" name="score_B" size="1"></u></p>
<input type="hidden" name="team_B" value="<?php echo $prelimTeam[$i]; ?>">
</form><br><br><br>
<?php
$game_num++;
$e=$e+2;
}
$i++;
}
?>
Without knowing the inputs or seeing the result, it's hard to tell for sure, but it looks like you might be generating multiple instances of this form on the same page, giving you multiple page elements named "score_A" and "score_B". document.getElementById will then become a bit ambiguous.
Since you're already sending the form object, use that instead:
var scoreA = form.score_A.value;
...
There is essentially a single problem with your code. You have multiple instances of the same ID.
To fix it, try something like this.
<input type="text" class="small score_A" name="score_A" size="1" />
Similarly
<input type="text" class="small score_B" name="score_B" size="1" />
Now, you can write a querySelector in your JS
function CompareScores(form) {
var a = form.querySelector('.score_A').value;
var b = form.querySelector('.score_B').value;
//do something
}

Categories