Rendering javascript code in php document - php

I'm a beginner to PHP and I have a quick question. Is it possible to have javscript code injected into a document through php?
For example, suppose I wanted to inject a button that called a function after a form is filled out:
<html>
<head>
<script type = text/javascript>
function func() {
...
}
</script>
</head>
<body>
<form action = 'welcome.php' method = 'post>
Name: <input type = 'text' name = 'fname' />
<input type = 'submit' value = 'submit' />
</form>
<?php
if (isset($_POST['fname'])) {
echo '<input type = button onclick = func />'
}
?>
</body>
</html>
Would this work? If not, why not?
Any help would be great

Will work fine - just remember to close your quoted strings :
<form action='welcome.php' method='post'> // add ' here
Name: <input type='text' name='fname' />
<input type='submit' value='submit' /> // removed a couple of spaces (not required)
</form>
<?php
if (isset($_POST['fname'])) {
echo '<input type="button" onclick="func" />'; // added some quotes and a semicolon
}
?>
I have removed the spaces between the attributes and the values in HTML from type = "something" to type="something" although I can't find the "official" specification on this. It seems that the spaces are perfectly valid ...I think its my personal preference to have no white space there .....

Try:
echo '<input type="button" onclick="' . $_POST['fname'] . '" />';
SAMPLE
If fname=doSomething then use:
echo '<input type="button" onclick="' . $_POST['fname'] . '()" />';
and your rendered HTML would be:
<input type="button" onclick="doSomething()" />
Then you'd just need your function somewhere:
<script>
function doSomething() { }
</script>

If your current page is welcome.php and you ran this code, you would press the Submit button and the page would reload and have your new button.
But the best way to see whether this works for you or not is to run it. Why don't you try that first?

Related

PHP multiple forms

So the issue I'm running into is I have a project with nested forms to select options and for some reason I cant get it to get beyond the first form. If you run this and select the first button it correctly displays the second button, but after that it just returns to the beginning.
How do I do this correctly? I've tried various methods such as isset, using functions, wiping the $_POST variable, etc and to no avail. Would Google or Stackoverflow this but I'm not quite sure what this problem is called.
This is all being done within a single php file because I don't want to have to deal with leaving the page, and this started out as a simple assignment that I've greatly expanded to fit my needs. Also I know nothing of Javascript and have no interest in using it.
<html>
<body>
<?php
echo <<< HERE
<form method = "post">
<input type = "submit" name = 'button' value = 'Do thing 1'>
<br>
</form>
HERE;
$button = $_POST['button'];
if ($button == 'Do thing 1'){
echo <<< HERE
<br>
<form method = "post">
<input type = "submit" name = 'button2' value = 'Do another thing'>
</form>
HERE;
$button2 = $_POST['button2'];
if ($button2 == 'Do another thing'){
echo 'doing another thing';
}
}
?>
</body>
</html>
The way I would solve this kind of issue is by sending all the fields and naming the buttons:
<form>
<input name="input_1">
<input name="input_2">
<button type="submit" name="button" value="button">Button</button>
<input name="input_n">
<button type="submit" name="button" value="button2">Button2</button>
</form>
Then once submitted:
if($_POST['button'] == 'button') {
/* sanitize input 1*/
/* sanitize input 2*/
/* do something */
}
if($_POST['button'] == 'button2') {
/* sanitize what you need */
/* sanitize input n*/
/* do something */
}

Javascript function inside php

I try to create a button in php and increase or decrease its value (inside the text input) on click.
<?php
echo "<script>
function inc(elem)
{
x = elem.value;
//alert('dsadasdasdsadasdas');
if(x<31)
{
x= x+1;
}
alert(x);
elem.value = x;
}
</script>";
echo '<form action="tziros.php" method="post">';
echo '<input type="text" value="1" name="tziros_imeras">';
echo '<br>';
//echo '<input type="button" value="ADD +" onClick="inc(document.getElementById("tziros_imeras"))">';
echo '<input type="button" value="ADD +" onClick="inc(document.getElementById(\'tziros_imeras\'))">'
//echo '<input type="button" value="DEC -" onClick="dec();">';
echo '<input type="submit" name="submit_tziros_meras" value="OK">';
echo '</form>';
?>
Problem is that javascript is not running at all .
EDIT :
after reading your answers i came up with this:
js:
function inc(elem)
{
elem.value++;
}
and on the form:
echo '<input type="text" value="1" id="tziros_imeras" name="tziros_imeras">';
So now at last, the js is running .
You're looking for tziros_imeras by ID (getElementByID) but you have only the name property set up to tziros_imeras
you have only the method inc() - you're missing the method dec()
and most important:
you're incrementing x which is a local variable (it doesn't affect the actual element), you should do instead:
elem.value += 1;
Update your PHP to use this form so it is easier to read and debug:
echo reference
echo <<<END
content here will be printed
multiple lines!
END;
I'm not sure I believe you, that is is not "running". Insert an alert in your JavaScript to verify.
alert('I am alive');
This part of the code:
echo '<input type="button" value="ADD +" onClick="inc(document.getElementById("tziros_imeras"))">';
Needs to be like this:
echo '<input type="button" value="ADD +" onClick="inc(document.getElementById(\'tziros_imeras\'))">';
The JS being outputted was like this:
onClick="inc(document.getElementById("tziros_imeras"))"
Which, as you'll notice, has messed up quotes. This is what was causing the JS to fail to run (look in your browser console and you'll see the errors as well).
As some others have said, you have some JS errors as well, but this is the main issue related to your question.

Add variable into (specify text field) on the previous page

I have been looking for a way to add the information (string) from a variable in the previous page.
As far as I know this should be possible using javascript somehow.
New one couldn't get the old one to work properly..
<script type="text/javascript">
function newPopup(url) {
popupWindow = window.open(
url,'popUpWindow','height=510,width=350,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
</script>
Armory Avatar
I have that piece of code that opens the link into a new popup window(which remembers the url of the previous page).
In this window people can insert some information about there WoW character and the realm this character is on. After they do this and hit submit the site displays the url for the avatar retrieved from the blizzard armory.
http://eu.battle.net/static-render/eu/(imagepath)
Code for the popup page: Updated this current code (7-4-2012)
<?php
if (!isset($_POST['submit'])) {
?>
<!-- The fill in form -->
<html>
<head>
<title>Armory Avatar</title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
Character Name:<input type="text" size="12" maxlength="50" name="cname"><br />
Realm Name:
<select name="rname">
<optgroup label="English Realms">
<option value="aerie-peak">Aerie-Peak</option>
<option value="agamaggan">Agamaggan</option>
<option value="aggramar">Aggramar</option>
etc etc etc.
</optgroup>
</select><br />
<input type="submit" value="submit" name="submit">
</form>
<?php
} else { //If form is submitted execute this
$charname = $_POST["cname"]; //input character name
$realmname = $_POST["rname"]; //input realm name
$charurl = urlencode(utf8_encode($charname)); //prepares character name for url usage
$realmurl = 'http://eu.battle.net/api/wow/character/'.$realmname.'/'; //combines the basic url link with the realm name
$toon = $realmurl.$charurl; //adds the charactername behind the realm url
$data = #file_get_contents($toon); //retrieves the data from the armory api
if ($data) {
// if armory data is found execute this
$obj = json_decode($data); //converts the data from json to be used in the php code ?>
<img src='http://eu.battle.net/static-render/eu/<?php echo $obj->thumbnail; ?>'> </img><br /> <?php //Is url link to image
$armoryname = utf8_decode($obj->name); //makes the name readable again
echo "Name: " . $armoryname . "<br />"; //character name
echo "Level: " . $obj->level . "<br />"; //character level
echo "Achievement Points : " . $obj->achievementPoints . "<br />"; //Achievement Points
if ( $obj->gender == 1 ){ //Deteremines the gender of the character
echo "Gender : Female <br />" ; //displays gender as female
}else{
echo "Gender : Male <br />" ; //dispalays gender as male
}
$image = "http://eu.battle.net/static-render/eu/".$obj->thumbnail;
?>
Image: <a href='http://eu.battle.net/static-render/eu/<?php echo $obj->thumbnail; ?>'> http://eu.battle.net/static-render/eu/<?php echo $obj->thumbnail; ?></a><br />
<!--Button submit code-->
<script type="text/javascript">
$('button.cancel_link').click(function() {
// Change the value of the input with an ID of 'avatarurl'
// with the dynamic value given to you by the external JSON link
window.opener.getElementById('avatarurl').value = '<?php echo $image; ?>';
});
</script>
<input> <!-- The button here -->
<?php
}
else { // if armory data is not found execute this ?>
error code stuf
}
}
?>
Now i need this line of code:
$image = "http://eu.battle.net/static-render/eu/".$obj->thumbnail;
To be returned when the window is closed or simply by hitting another submit button(prefered to happen on close over button). And when either of those happen it needs to insert this into this string:
<input type="text" class="textbox" name="avatarurl" size="25" maxlength="100" value="{$avatarurl}" /></td>
The texbox called avatarurl.
Hopefully any of you know how to modify or create a javascript that does this for you. Since my php is already severely limited and my javascript knowledge is next to none.
You need to modify the way you're closing your pop-up window. Try something like this:
// When a BUTTON with the class name 'cancel_link'
// is clicked, it activates the following
$('button.cancel_link').click(function() {
// Change the value of the input with an ID of 'avatarurl'
// with the dynamic value given to you by the external JSON link
window.opener.getElementById('avatarurl').value = '<?php echo $image; ?>';
});
You need to make sure your closing link has cancel_link as its class name, and that your input element in your parent document has an id of avatarurl.
So after searching trying and thanks to #Jamie i knew where to look.
I found http://www.codingforums.com/showthread.php?t=213298
And this was finally the thing that worked.
On the php page to open it i added:
<script type="text/javascript">
function open_pop(){
window.open('armory.php','AvatarArmory','height=510,width=350,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
</script>
<html>
.....
<input type="button" value = "OpenArmory" onClick="open_pop()" />
And added id="blogbox" to the input for the textbox.
<input type="text" class="textbox" name="avatarurl" size="45" value="{$avatarurl}" id="blogbox"/>
On the armory.php page i added this button with the javascrip function:
<script type="text/javascript">
function pops(avatar){
textcontent=opener.document.getElementById("blogbox").value;
opener.document.getElementById("blogbox").value = textcontent + " " + avatar;
}
</script>
<input type="button" value = "Insert Avatar.." onClick="pops('<?php echo $image; ?>');window.close()" />
And that worked perfectly.
Thank you jamie for the help.

Simple Php Echo

I am just starting to learn php, how would I initiate a echo statement after a submit button is pushed, or even a anchor tag.
Here is my code so far
form name="myform" method="get" actions="madlib01.php"
Name: <input type="text" name="name" /> <br />
<input type="submit" name="submit" />
form
<?php
$Name = $_GET['name'];
$hello .= "Hello $Name";
echo $hello //I would prefer the echo to happen after the submit button is hit
?>
the correct attribute for your form tag is "action", not "actions"
When the form is submitted, a new request is sent to the server (in your case, using GET).
So to do it all in one page:
form.php:
<form action="form.php" method="GET">
<input type="text" name="name"/>
<input type="submit">
</form>
<?PHP
if (! empty($_GET['name'])){
echo 'Hello, ' . $_GET['name'];
}
?>
You will first need to check if PHP has received your GET parameter using isset or array_key_exists:
if(isset($_GET['name']) && !empty($_GET['name'])) {
$Name = $_GET['name'];
echo "Hello $Name";
}
or:
if(array_key_exists('name', $_GET) && !empty($_GET['name'])) {
$Name = $_GET['name'];
echo "Hello $Name";
} else {
//example: default to something if nothing has been passed
echo "Hello Guest";
}
Also note, if you're submitting to the same page, you can omit the action attribute from your form tag altogether:
<form method="GET">
echo $hello
You've just gained an HTML-injection vulnerability. If someone sends your user to:
http://www.example.com/madlib01.php?name=<script>stealYourCookies()</script>
you've got problems.
Yes, this is a My First PHP Script. That doesn't make security optional. This is a mistake every tutorial makes: teaching bad practice from the start, treating correctness (and security, which is a subset of correctness) as an optional extra.
The result is that most PHP code out there is full of holes. But there's no need for yours to be! Every time you place a pure-text string into a surrounding HTML context, escape it properly:
echo htmlspecialchars($hello);
I tend to define a function with a shorter name than ‘htmlspecialchars’ to do that for me, as I'm lazy.
<?php
function h($text) {
echo(htmlspecialchars($text, ENT_QUOTES));
}
$name= '';
if (isset($_REQUEST['name']))
$name= trim($_REQUEST['name']);
?>
...
<?php if ($name!=='') { ?>
<p> Hello, <?php h($name); ?>! </p>
<?php } ?>
<form method="get" action="madlib01.php">
<p>
<label for="namefield">Name:</label>
<input id="namefield" type="text" name="name" />
</p>
<p>
<input type="submit" />
</p>
</form>
Now if you say your name is Mister <script>, the page will greet you exactly as such, angle brackets and all, instead of trying to run JavaScript. This is the correct output and thus also secure.

expanding a quoted string within another string

I have two variables containing some html code, and another variable containing code for a html form. I am trying to expand a string within the second to pass it as a parameter to a function, however this causes some errors.
My make popup function is very simple:
function popup(htmlcode){
child1 = window.open ("about:blank");
child1.document.write(htmlcode);
child1.document.close();
}
The code that uses the above function
<?php
$blah = "<h1>Well</h1>"; $test = "<h2>Done</h2>";
echo '<script type="text/javascript" src="fetchlayers.js"></script>';
$formcode = "<form action=\"process.php\" method=\"post\" enctype=\"multipart/form-data \">
<label for=\"file\">Filename:</label>
<input type=\"file\" name=\"file\" id=\"file\"/>
<br />
<input type=\"submit\" name=\"submit\" value=\"Submit\" onclick=\"setTimeout(function() { sendInfo(\"".$blah."\", \"".$test."\"); } ),1250);\" />
</form>";
echo "<h1>hello</h1>
<div id='form'>
<a href='#' onclick=\"popup('" . htmlentities($formcode) . "'); return false;\">
click here</a>
</div>";
This produces decent enough html code, however firebug gives me an error that I have an unterminated string lateral. I cannot find where this is. I understand the way I have done this is not ideal, but I am learning and do not know a better way at present. I appreciate any input
edit: OK, so the problem was that I had unterminated string literals, which were \n characters. I made the string into one line and it called the function correctly.
Is it not possible to break one echo statement into multiple lines?
Now the problem is with the html generated in the popupwindow. Some of the code is actually printed to the screen, why is this?
<form action="process.php" method="post" enctype="multipart/form-data "><label for="file">Filename:</label><input name="file" id="file" type="file"> <br><input name="submit" value="Submit" onclick="setTimeout(function() { sendInfo(" type="submit"><h1>Well</h1>", "<h2>Done</h2>"); },1250);" /></form>
See the image here:
A better way to do this is to open an HTML or PHP page that already has the form code in it, instead of opening about:blank and passing it dynamically.
There is no reason you should ever have to pass HTML into a Javascript function just so it can be directly written to document.
If you absolutely have to keep the popup function as is, I found a solution with help from this answer to "How do I escape a string inside javascript inside an onClick handler?".
<?php
$blah = "<h1>Well</h1>"; $test = "<h2>Done</h2>";
echo '<script type="text/javascript" src="fetchlayers.js"></script>';
$formcode = '<form action="process.php" method="post" enctype="multipart/form-data ">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"/>
<br />
<input type="submit" name="submit" value="Submit" onclick="setTimeout(function() { sendInfo(\\x27'.$blah.'\\x27, \\x27'.$test.'\\x27); }, 1250);" />
</form>';
echo "<h1>hello</h1>
<div id='form'>
<a href='#' onclick='popup(\"" . addslashes(str_replace("\n", ' ', $formcode)) . "\"); return false;'>
click here</a>
</div>";
?>
Before edit:
Maybe you can do it differently.
Javascript functions:
function popup(id, params){
var html = document.getElementById(id).innerHTML;
if (params != undefined) {
html = findAndReplaceStrings(html, params);
}
var child1 = window.open ("about:blank");
child1.document.write(html);
child1.document.close();
}
function findAndReplaceStrings(text, json) {
for (var x in json) {
text = text.replace(x, json[x]);
}
return text;
}
HTML hidden code:
<div style="display:none;" id="process">
<form action="process.php" method="post" enctype="multipart/form-data ">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"/>
<br />
<input id="submit" type="submit" name="submit" value="Submit" onclick="setTimeout(function() { sendInfo('{param1}', '{param2}'); } ), 1250);" />
</form>
</div>
HTML link with json:
<a href="#" onclick="popup('process', {'{param1}':'<h1>Well</h1>', '{param2}':'<h2>Done</h2>'}); return false;">
click here</a>
You must escape the carriage returns (\n) by doing
$formcode = str_replace("\n", "\\n", $formcode);
You also have to escape the quotes
$formcode = str_replace("'", "\\'", $formcode);
You can combines those two lines into a single one:
$formcode = str_replace(array("\n", "'"), array("\\n", "\\'"), $formcode);
The submit button has an extra ) which closes the setTimeout function too early. The specific spot is inside:
} ),1250
you should also probably think about using single quotes inside the php string to make it all easier to read. And because you're using double quotes you don't have to break out of the string to insert the content of the variables $blah and $test.
something like this should work:
$formcode = "...
<input type='submit' name='submit' value='Submit'
onclick='setTimeout(function() { sendInfo(\"$blah\", \"$test\"); },1250);' />
...
";
EDIT:
looks like it's closing the onclick too early now. Matching these as the start and end quotes:
onclick=\"setTimeout(function() { sendInfo(\"
I changed the sendInfo line to the following, ran it and looks like it's working. The single quote is escaped here so it doesn't prematurely close the call to popup().
sendInfo(\'".$blah."\', \'".$test."\');

Categories