Get PHP variable to javascript - javascript

I cant seem to find the answer for this one. I need to grab a PHP variable and insert it into javascript.
Here is an example of what I have in the body of a PHP page:
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
var info = "<?php Print($info); ?>";
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(info);
});
});
});
</script>
<?php
$info="some info";
?>
<form id="frm1" method="post" action="somepage.php">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>
So the problem is that the alert pops up but doesn't echo the $info string. Obviously i'm missing the right way to grab a PHP variable. Please help.

If the php variable is visible inside the inner HTML, you could do something like this to grab the variable:
HTML:
<span class="variable-content"><?php echo $variable; ?></span>
jQuery:
var php_variable = $(".variable-content").text();
alert(php_variable);

Change:
alert(info);
to:
alert('<?php echo "some info"; ?>');

It looks to me like you are declaring the variable after you use it. So there is nothing in $info.
try:
<?php
$info="some info";
?>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
var info = "<?php echo $info; ?>";
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(info);
});
});
});
</script>
<form id="frm1" method="post" action="somepage.php">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>

try this
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<span id="info" hidden><?php
$info="some info";
echo $info;
?></span>
<form id="frm1" method="post">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
var info = $("#info").text();
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(info);
});
});
});
</script>
</body>
</html>

Primary issue with your example code
All of the PHP executes ahead of the JS. PHP executes, then outputs Your HTML and JS to the browser where they are rendered/executed/etc.
As such, your Print of $info is executing before your declaration and definition of $info. You need to define it, then output it.
Further issues you should consider
Once this is solved, you'll eventually run into issues with simply spewing data into the middle of JS. It is not easily maintained, and unprepared data will eventually break your JS syntax. When I have to do such a thing, I generally separate the two as much as possible:
<?php
// declare and define the data
$info = "foo";
?>
<script>
// prepare an IIFE which takes the data as a param
(function (info) {
// inside this function body you can use the data as you
// please without muddling your JS by mixing in PHP
alert(info);
}(
// in the invoking parens, output encoded data
<?= json_encode($info) ?>
));
<script>
Another benefit of this approach is that you can pass any PHP data structure to JS without changing the approach in any way. (As opposed to using inputs or element texts where you'd need to parse the JSON and keep track of which elements contain which values)

If you don't want to use JQuery you could put the php value into a hidden input and get it from the hidden variable with JavaScript documentGetElementById... that way you can keep your script in the head, which seems to meet your requirements. Either the hidden span as per #Miko or:
<input type="hidden" id="php_info_data" name="php_info_data" value="<?php echo $info; ?>" />
and in your header script which executes after the body has loaded:
var info = documentGetElementById('php_info_data').value;

<?php
$info="some info";
?>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
var info = "<?php echo($info); ?>";
alert(info);
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(info);
});
});
});
</script>
<form id="frm1" method="post" action="somepage.php">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>

Try this
var info = "<?php echo $info; ?>";

try this
<?php
$info="some info";
?>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(<?php echo $info;?>);
});
});
});
</script>
<form id="frm1" method="post" action="somepage.php">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>

you can convert PHP variable to JSON and then send it Javascript, becoz JSON
is supported by all language
Example
var a=<?php echo json_encode($info); ?>
alert(a);
or simply
var a=<?php echo $info; ?>
alert(a);
<?php $info=10; ?>
<script>
var a=<?php echo $info; ?>;
var a1=<?php echo json_encode($info+10); ?>;
alert(a);
alert(a1);
</script>

Related

Transform GET request to POST request to load generated PDF file

In an html page I have a button that loads a generated pdf:
<button onclick='getpdf()'>GET PDF</button>
<script>
function getpdf(){
data={
var1: 'var1',
var2: 'var2'
};
window.open('genpdf.php?var1='+data['var1']+'&var2='+data['var2'], '_new');
}
</script>
genpdf.php is something like this:
<?php
require('fpdf/fpdf.php');
$var1 = $_GET['var1'];
$var2 = $_GET['var2'];
$pdf = new PDF();
/* ......... */
$pdf->Output('D','generated.pdf');
?>
My question is:
How can I change my code to pass parameters with POST method?
SOLUTION
ADyson suggested me this solution:
<form id="pdf" action="genpdf.php" methon="POST" target="_new">
<input type="hidden" name="var1" />
<input type="hidden" name="var2" />
<button onclick='getpdf()'>GET PDF</button>
</form>
<script>
function getpdf(){
$("#pdf input[name=var1]").val('var1');
$("#pdf input[name=var2]").val('var2');
$("#pdf").submit();
}
</script>
and
<?php
require('fpdf/fpdf.php');
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$pdf = new PDF();
/* ......... */
$pdf->Output('D','generated.pdf');
?>
and it works fine!
BUT
If I wanted to do that without the use of a form, how could I do?
If you want to implement without coding HTML then use following Javascript
var myform = document.createElement('form');
myform.style.display = "none";
myform.name='PdfGenOrSomethingElse';
myform.method='POST';
myform.action='genpdf.php';
myform.target='_blank';
var var1=document.createElement('input');
var1.type='text';
var1.name='var1';
var1.value='Put/update your value';
var var2=document.createElement('input');
var2.type='text';
var2.name='var2';
var2.value='Put/update your value';
myform.appendChild(var1);
myform.appendChild(var2);
document.body.appendChild(myform);
myform.submit();
Notice the form will not be displayed on the page. "display" property is set to "none".
You don't need any javascript function for this. Just use FORM element with action post:
<form action="genpdf.php" method="post" target="_blank">
<input type="text" name="var1" value="" />
<input type="text" name="var2" value="" />
<button type="submit ">GET PDF</button>
</form>
The don't forget to use $_POST instead of $_GET in your PHP script.

Appended element goes undefined when being passed over

Hi i have this code where everclick appends a DOM element where the user can pick what he wants then submits it to another page.
<form action="view.php" method="post">
<textarea name="paragraph[]"></textarea><input type="button" onclick="addparagraph();" value="+">
</input>
<select name="font[]">
<option>Tohoma</option>
<option>Arial</option>
</select>
<div id="firstpart"></div>
<input type="submit" value="submit"/>
</form>
<script>
function addparagraph(){
var string = '<textarea name="paragraph[]"></textarea>'+
'<select name="font[]"><option>Tohoma</option><option>Arial</option></select>';
jQuery('#firstpart').append(string);
}
</script>
once submitted it does not get the value of the appended elements
here is the view.php part
foreach($_POST['paragraph'] as $count => $value){
echo "$value";
echo "$_POST['font'][$count];
}
it appends the elements but it does not display the values of the appended array.. it gives an error offset undefined
1.You need to add a jQuery library to make your code to work.
2.You need to change PHP code too.
The code needs to be like below:-
HTML PAGE:-
<form action="view.php" method="post">
<textarea name="paragraph[]"></textarea><input type="button" onclick="addparagraph();" value="+"></input>
<select name="font[]">
<option>Tohoma</option>
<option>Arial</option>
</select>
<div id="firstpart"></div>
<input type="submit" value="submit"/>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function addparagraph(){
var string = '<textarea name="paragraph[]"></textarea>'+'<select name="font[]"><option>Tohoma</option><option>Arial</option></select>';
jQuery('#firstpart').append(string);
}
</script>
PHP PAGE:-
<?php
foreach($_POST['paragraph'] as $key => $value){
echo $value;
echo "<br>";
echo $_POST['font'][$key];
}
Your loop should look like this:
foreach($_POST['paragraph'] as $count => $value){
echo $value;
echo $_POST['font'][$count];
}

checking isset at bottom of page not working

I have a dilemma (which I am yet to find a way around). For some reason, PHP doesn't want to check if $_POST["login"] at the bottom of the <body> tag within my document.
It will work if it is put at the very top of the document, or even the top of the <body> tag. However, if I put it at the top of the document / <body> tag, the output JavaScript will not execute!
For example, this is the document (where the PHP will not execute):
<form>
<span id="example-element">Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
<?php
if(isset($_POST["login"])){
echo "
<script>
document.getElementById('example-element').style.display = 'block';
</script>"
}
?>
If I am to do something like this, however (the PHP will execute):
<?php
if(isset($_POST["login"])){
echo "
<script>
document.getElementById('example-element').style.display = 'block';
</script>"
}
?>
<form>
<span id="example-element">Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
But due to how JavaScript compiles, it will throw an error saying how it cannot set a style on a null element.
I have no idea how to get around this dilemma, so all help is appreciated!
Cheers.
<form>
<span id="example-element">Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
<?php
if(isset($_GET["login"])){
echo "<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('example-element').style.display = 'block';
}, false);
</script>";
}
?>
Check if this works..... I've added the display code inside the DOMContentLoaded event and change the $_POST variable to $_GET. Works fine in my local system.
You can do it as follows
<style>
.someClass {
display: block;
}
</style>
<?php
if(isset($_POST["login"])){
$hasClass = true;
}
?>
<form method="post">
<span id="example-element" class=<?php if(isset($hasClass)==true) echo "someClass"; ?> >Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
The other problem with your code is that you are not setting method of your form and by default it is GET where as in php you were looking for POST request.
You could solve it either by using $_REQUEST in php when you are not sure about the method.
Actally php executes before javascript.
Change like this
<script>
var isSubmit = "<?php isset($_POST['login'])?true:false; ?>";
if(isSubmit){
document.getElementById('example-element').style.display = 'block';
}
</script>"

send php post variable to url using javascript when button is clicked

I have a php page which gets $page and $user using post method, I also have a button that i want, to open a URL in the same window using $page and $user variables when clicked, to use them with $_GET[] function.
i want my URL be like:
http://www.test.com/test.php?page=$page&user=$user
my code is like this:
<?php
$page=$POST_['page'];
$user=$POST_['user'];
<?
<html>
<head>
function openurl() {
var user=<?php echo "$user";?>;
var page=<?php echo "$page";?>;
open('www.test.com/test.php?page='+page'&user='+user,'_self');
}
</head>
<body>
<button onclick="openurl()" type="button">open url</button>
</body>
</html>
There is no need for scripting at all
If you want GET:
<?php
$page=$GET_['page']; // should be sanitized and you can use REQUEST for either
$user=$GET_['user'];
$parm = "page=".$page."&user=".$user;
?>
Open URL
If you need to post:
<form action="test.php" method="post">
<input type="hidden" name="page" value="<?php echo $page; ?>"/>
<input type="hidden" name="user" value="<?php echo $user; ?>"/>
<input type="submit" value="Open URL" />
</form>
Change these lines:
<?php
$page=$POST_['page'];
$user=$POST_['user'];
<?
....
var user=<?php echo "$user";?>;
var page=<?php echo "$page";?>;
open('www.test.com/test.php?page='+page'&user='+user,'_self');
to this:
<?php
$page=$_POST['page']; //incorrect $_POST declaration
$user=$_POST['user']; //incorrect $_POST declaration
?> //php tag incorrectly closed
....
var user=<?php echo $user;?>; //echoing a variable not string (no need for quotes)
var page=<?php echo $page;?>; // echoing a variable not string (no need for quotes)
open('www.test.com/test.php?page='+page+'&user='+user,'_self'); // link was broken, forget to put '+' after page variable in link.
You can create a form and via Javascript just run YOURFORMNAME.submit();
Use href in javaScript to move to another location:
location.href="www.test.com/test.php?page='+page'&user='+user"

passing javascript throught textarea inside a form

I would like to ask a question.
Is there a way to pass jquery script over textarea and being accepted by php with $_POST function?
just like w3schools did, I've tried but the jquery script are missing and I don't know why..
Please somebody help me. Thank you!
<form action="showHTML.php" method="post" >
<textarea name="html" id="hello">
<script src="lib/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("body").css({backgroundColor:"red"});
});
</script>
</textarea>
<form>
And this is my php file that i used to grab the content from the $_POST
<?php
if(isset($_POST['html']) and !empty($_POST['html'])){
$data = htmlentities($_POST['html']);
}else{
echo '<p>Edit the HTML to the right.</p>';
}
echo html_entity_decode($data);
?>
<script src="lib/jquery.min.js"></script>
<form action="showHTML.php" method="post" >
<textarea name="html" id="hello">
$(document).ready(function(){
$("body").css({backgroundColor:"red"});
});
</textarea>
<form>
Now get the script as text from showHTML.php and process it from there. I guess you can't put script tag inside text area like what you have done.
your code should look like this: close your form tag and add a button to submit.
<script>
$(document).ready(function(){
$("body").css({backgroundColor:"red"});
});
</script>
<form action="showHTML.php" method="post" >
<textarea name="html" id="hello">
</textarea>
<input type="submit" value="submit"/>
</form>
----^
php:
<?php
if(isset($_POST['html']) and !empty($_POST['html'])){
$data = htmlentities($_POST['html']);
}else{
echo '<p>Edit the HTML to the right.</p>';
}
echo html_entity_decode($data);
?>

Categories

Resources