Is it possible to pass javascript variable in getElementbyId()??
This is my radio code:
echo '<td><input id="dis1" type="radio" name="select" value="1" /></td>';
echo '<td>'.$poke[0]."<br>";
echo 'Level:'.$level[0]."<br>";
echo 'Health:'.$health[0]."<br></td>";
The below is my javascript code...in which first the id value is stored in PHP cvariable and then stored in javascript and using this javascript variable, I will disable the radio button. !
<script>
var dis_value = <?php echo $dis_value; ?>; //$dis_value = dis1
document.getElementById("dis_value").disabled=true;
</script>
But dunno why it seems not to be working?? are there any constraints which I need to follow if I am using a variable in getElementbyID ???
First, if you are generating JavaScript with PHP, then you need to generate real JavaScript. You can't just dump a variable into the script.
As it stands, your generated JavaScript is going to look like:
var dis_value = dis1;
which will throw a reference error since dis1 is not defined.
Convert the contents of your PHP string into a JavaScript string:
var dis_value = <?php echo json_encode($dis_value); ?>
Second, if you want to use a variable, then use a variable, not a string literal.
Remove the quotes.
document.getElementById(dis_value) …
That said, why are you bothering to involve JavaScript in this in the first place?
<td><input id="dis1" type="radio" name="select" value="1" <?php
if ($dis_value == "dis1") {
echo "disabled";
}
?>/></td>
try to remove quotes from var
<script>
var dis_value = "<?php echo $dis_value; ?>"; //$dis_value = dis1
document.getElementById(dis_value).disabled=true;
</script>
Try this.
<script>
var dis_value = '<?php echo $dis_value; ?>';
document.getElementById(dis_value).disabled=true;
</script>
Related
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>
I have a JavaScript function for scrolling of table when button is click but I have multiple tables in my code and cant use multiple function for each table I want to store the id's of all table in dynamic way using PHP.
<script type="text/javascript">
// Do something in JavaScript
var x = <?php echo $row_[document_id]; ?>;
// etc..
</script>
document_id is were value are accessed dynamically in PHP.
Instead of using
var x = <?php echo $row_[document_id]; ?>;
you can use something like this:
<?php
echo '<script>var x = ' . $row_document_id . ';</script>';
?>
If data is a string, you can use double quotes:
<?php
echo '<script>var x = "' . $row_document_id . '";</script>';
?>
Also it is preferred to use let instead of var.
Hope that helped.
Save the PHP variable value in HTML hidden input element.
<input type="hidden" value="<?php echo $row_[document_id]?>" id="getValue">
And then get the value from JavaScript or jQuery.
var x = $("#getValue").val();
When I load a php page, i put within a javascript function, a name. The problem comes when this string has special chars like '.
Here I paste the code of a click event:
showSocialShare(event, '<?php echo $object->slug; ?>', '<?php echo htmlspecialchars($object->title); ?>', '<?php echo $object->image; ?>')
I thought that the function htmlspecialchars code somehow the string but the result is:
showSocialShare(event, '4049269', 'collection-'Noun'', '/img/Original.jpg')
As can be seen, at the second parameter, the name contains characters like ' and arises an error.
How can I avoid this?
Never output text from PHP directly into a Javascript context. As you're finding out, it's VERY easy to generate JS syntax errors.
Always use json_encode: e.g. given this
<?php $foo = 'bar'; ?>
<script>
var badly_broken = <?php echo $foo ?>;
var working_fine = <?php echo json_encode($foo); ?>;
</script>
You'll end up with
<script>
var badly_broken = bar; // oops - undefined variable "bar"
var working_fine = "bar";
</script>
And note that if you're outputting JS into an HTML attribute, you not only have to generate valid Javascript, you have to output valid HTML AS WELL:
<?php $foo = array('bar' => 'baz'); ?>
<a onclick="brokenCall(<?echo json_encode($foo) ?>)">
<a onclick="workinCall(<? echo htmlspecialchars(json_encode($foo)) ?>)">
produces:
<a onclick="brokenCall({"bar":"baz"})">
^--start attribute
^--end attribute - ruhroh
<a onclick="workingCall({"bar":"baz"}")>
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); ?>";
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);