passing javascript variable in php file to html [duplicate] - javascript

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I am just wondering on one thing that I cannot solve until now.
I have one php file, with the following code.
doInit.php
<?
include 'connect.php';
session_start();
if(isset($_SESSION['detailid'])){
$detailid = $_SESSION['detailid'];
$resutlinit=mysql_query("select Nama,Kelas,Ranking,Level,Exp,Sekolah from MsDetail where DetailID='$detailid'");
if(mysql_num_rows($resutlinit)!='0'){
$row = mysql_fetch_array($resutlinit);
$nama = $row['Nama'];
$kelas = $row['Kelas'];
$ranking = $row['Ranking'];
$level = $row['Level'];
$exps = $row['Exp'];
$sekolah = $row['Sekolah'];
}else echo("Nothing here, try to more detail on your code");
}else {header("location:index.html");}
?>
<script type="text/javascript">
var nama = "<?= $nama ?>";
var kelas = "<?= $kelas ?>";
var ranking = "<?= $ranking ?>";
var level = "<?= $level ?>";
var exps = "<?= $exps ?>";
var sekolah = "<?= $sekolah ?>";
//document.writeln(nama);
//document.writeln(kelas);
//document.writeln(ranking);
//document.writeln(level);
//document.writeln(exps);
//document.writeln(sekolah);
</script>
and I want to write the javascript file on my inside div.
This is what I wrote in my div HTML Editor.
<script type="text/javascript">
document.writeln(nama);
</script>
and this doesn't work.
I tried to add some src things on PHP File like
<script type="text/javascript" src="target.html"></script>
but it has no luck.
and I tried to add that src into the target html like
<script type="text/javascript" src="doInit.php"></script>
and this too is not working for me.
Any suggestion how to solve this? Thanks for attention :)
Sorry for editing after 2 answers are here.

First, to set textbox value document.writeln is not what you need. You should do it like this:
<input id="myInput" type="text"/>
<script type="text/javascript">
document.getElementById('myInput').value = myInputValue;
</script>
Also, you must be sure, that all needed JS loaded in appropriate order.
NOTE: I see, you're not using any PHP framework. This way, one possible approach I might suggest here to optimize your code is to use standard PHP function json_encode. But then you should compound all your JS vars into one object:
PHP:
<?php
// Database work
if(mysql_num_rows($resutlinit)!='0'){
$row = mysql_fetch_array($resutlinit);
}
// ...
?>
<html>
<head>
<script type="text/javascript">
var data = <?php echo json_encode($row); ?>;
</script>
</head>
<body>
<form>
<input id="myInput" type="text"/>
</form>
<!-- Here your form is already loaded -->
<!-- Perform any JS activity on page at end of body -->
<script type="text/javascript">
document.getElementById('myInput').value = myInputValue; // As it goes in database row
</script>
</body>
</html>
UPD: If you need to assign input value on page load only, you can do it in very simple way:
<input id="namaInput" type="text" value="<?php echo $row['Nama']"/>

document.writeline() replaces the contents of the whole page with the argument provided to it.
For the purpose of previewing the variable value use console.log() or, in more extreme use cases, alert().
As for using those values in your HTML document, you can use:
<input type="text" id="myNamaInputField" />
And in your javascript code:
var nama = "<?= $nama ?>";
document.getElementById("myNamaInputField").value = nama;
Which will populate your input field with the value of the javascript variable.
Pay attention to either put your javascript code after your HTML elements in your document, or delay it's execution until the DOM is ready for use.
Edit: To add the javascript text to the page, create a div, p or span element with the variable text and append it to the DOM.
In your javascript code:
var nama = "<?= $nama ?>";
var myNamaDiv = document.createElement('div');
myNamaDiv.innerHTML = nama;
document.body.appendChild(myNamaDiv);

Related

Passing PHP variable to Javascript Array

i want to pass PHP variable to Javascript array.
It is a test code, but in further i want to pass the printed product id's and name's to this ajax function to send it to cart
The code above is working without printing the button with echo.Any better ideas are welcome :)
<html>
<?php
$num=3;
echo "<button onclick='funkt('<?php echo $num ?>');'>cc</button>
";
?>
</html>
<script>
function funkt(x){
var c=x;
alert(c);
}
</script>
You weren't properly escaping the quotes inside the echo statement. Also, HTML attributes use double quotes (onclick="..."), not single quotes.
Try this:
<!DOCTYPE html>
<html>
<head>
<script>
function funkt(x) {
var c = x;
alert(c);
}
</script>
</head>
<body>
<?php
$num = 3;
echo "<button onclick=\"funkt('" . $num . "');\">cc</button>";
?>
</body>
</html>
Better option is to add an input field of type hidden and pass the number/name/ID to it. On submission of form or button click, you can fetch it wtih the field Id and pass the value to ajax.
<input type="hidden" id="number" value="<?php echo $num;?>" />
<script>
function funkt(x) {
var c = document.querySelector("#number").value;
alert(c);
}
</script>
You can try to declare variable inside "script" tag, and then use this variable in the javascript afterwards like this:
<?php $num = 5; ?>
<script>
var link_label = '<?php echo $num ?>';
//use your link_label value to load it in ajax here or in other files that has been loaded after this script
</script>

Simple Javascript for set multiple variables

Is there a Javascript way how to simple set multiple variables like in PHP?
example in PHP:
<?php
$var1 = 'first code or text';
$var2 = 'second code or text';
...
?>
and called enywhere simply by
<?php echo $var1; ?>
I founded for Javascript only "innerHTML" approach, associated with elements/id tags
<script>
var el = document.getElementById('variable1');
el.innerHTML = 'taste text';
</script>
with
<span id="variable1"></span>
Thanks
It is ok to do that
<script type="text/javascript">
var var1="first code or text";
var var2="second code or test";
</script>
Then you display it on your page by document.write() function which is in the core of javascript you have to call it at the place you want like this
<script type="text/javascript">
document.write(var1);
</script>

document.title funcion can't set it work with php

I have this line of code
<script type="text/javascript">
document.title = "<?php include('pot1.php');?>"
</script>
My pot1.php gives me an echo with one random number, but that code does not seem to work and I don't know why the echo doesn't appear in my title. Is anything wrong with the code?
pot1.php code:
<?php
#include_once('link1.php');
$cg = fetchinfo("value","info","name","current_game");
$cb = fetchinfo("cost","games","id",$cg);
$cb=round($cb,2);
echo '$'.$cb;
?>
This echo is working and is giving me values because I can see them in one div.
You should just do it like this:
<?php include('pot1.php');?>
Now we know that there is a variable set. Echo that into the title tag.
<script type="text/javascript">
document.title = "<? echo $cb ?>"
</script>
The way you're doing it now... I don't think you can include an entire PHP page and expect to behave like a simple string, even if that's all it returns.
Put the value you want inside a variable in the pot1.php file and use it on the title
<?php include('pot1.php');?>
<script type="text/javascript">
document.title = "<?php echo $yourVar;?>"
</script>

PHP variable, and change javascript properties

I have got the most biggest problem, I have see.
piece of code (just and example, the main example use database querys):
<?php $var1="999"?>
<script>
bigvar= <?php echo json_encode($var1); ?>;
var lolo = {
big: 2
}
lolo.big=bigvar;
alert(lolo.big);
</script>
Problem:
It does not recognize the PHP variable (it doesn't change to 999 value), and passing php value to javascript variable, doesn't work.How can help me ?.It is a big issue.
you should add quotes while assigning value from php variable to javascript, like as follows
<script>
bigvar= "<?php echo json_encode($var1); ?>"
var lolo = {
big: 2
}
lolo.big=bigvar;
alert(lolo.big);
</script>
and its </script>, not </scripts>
<script>
var bigvar= "<?php echo($var1); ?>"
var lolo = {
"big": "2"
}
lolo.big=bigvar;
alert(lolo.big);
</scripts>
The above example works fine for me..Try it
You have to add quotes around your php, so your JS know that this value is a string.
bigvar = "<?php echo json_encode($var1); ?>";

How do I pass a variable from one php file to a javascript file?

I am currently trying to make a site where I put in info in on my html side, it send the info to the php file and grabs info from another site depending on what you put in on the html side.
To make this more clear this is how it works:
You put in your username in the html site(where the javascript code
is).
Then it sends your username to the php file.
The php file gets the information, puts it in a link and request it.
It grabs information from this request (highscores page).
This is where it stops.
I don't know how to return the information to my javascript file.
This is my code:
html/javascript page:
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<script>
function test() {
var username = "Exzib";
window.location.href = "grabinfo.php?username=" + username;
}
</script>
</body>
</html>
This is my php file: (grabinfo.php)
<html>
<head>
</head>
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
echo $formatxp;
}
?>
<body>
</body>
</html>
So how do I proceed to send the $formatxp to my javascript?
Thanks
So what you do is execute:
window.location.href = "grabinfo.php?username=" + username;
This causes the browser to navigate to grabinfo.php and display the information that you want. Except that you don't want the information to be displayed, you want to retrieve it into a JavaScript variable, right?
To do so, don't set window.location.href. Instead call your script using AJAX. You'll find plenty of tutorials on AJAX out there. This will allow you to capture the output of your PHP script.
Change the following line
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
to
$formatxp = str_replace(array('$',',','.',' '),'',$xp);
And to pass the variable to Javascript you can do something like this.
<script type="text/javascript">
var $formatxp = '<?php echo $formatxp; ?>';
</script>
Write a script tag and set the variable equal to your PHP variable.
<script>
var thing = '<? echo $formatxp; ?>';
</script>
This is going to be easy as you already include jQuery. (Using ajax)
Look
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<label>Type your username:<input id="username" type="text"></label>
<input id="submit-button" type="button" value="Get my highscores!">
<p id="response"></p>
<script>
//When user clicks "submit-button" button
$("#submit-button").on('click', function() {
var username = $("#username").val();
//We request our php with the username
$.get("grabinfo.php?username=" + username, function(xpValue) {
//When we receive the response from php then we add it to a "p" tag
$("#response").text("LOL your xp is: "+xpValue+". NOOOOOOOB!!");
});
});
</script>
</body>
</html>
And that's it!
More info at http://api.jquery.com/on/
And http://api.jquery.com/get/
http://api.jquery.com/text/
http://api.jquery.com/val
And well the whole jQuery API documentation http://api.jquery.com
EDIT:
OH. You have to change grabinfo.php. It should only have this:
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
if(empty($formatxp)) {
echo "ERROR: Invalid could not find xp with username {$username}";
}
else {
echo $formatxp;
}
}
else {
echo "ERROR: Invalid arguments";
}

Categories