Is there anyway to store dynamic PHP value in JavaScript variable? - javascript

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();

Related

Javascript storing first value from foreach php function and keep repeating it

I have a javascript file that doing encoding for some string and implement it inside foreach PHP function to get values but unfortunately javascript holding and storing the first value from the foreach function only and keep repeating it
PHP
foreach ($json_content as $index => $array) {
echo '<textarea id="index" style="display:none">'.$index.'</textarea>';
echo '<textarea id="encoded'.$index.'" style="display:none">'.$aa_encode.'</textarea>';
echo '<script type="text/javascript" src="decdoe.js"></script>';
echo '<script type="text/javascript">function();</script>';
}
Javascript
var index = document.getElementById("index");
var AEncoded = document.getElementById("encoded"+index.value);
document.write(index.value);
document.write(function(AEncoded.value));
Output
000
firstvalue/firstvalue/firstvalue
What I missed?
Here is the solution
First: I added the ID inside a loop in the Javascript file like this
var i;
for (i = 0; i < $numberofloops ; i++) {
var AEncoded = document.getElementById("encoded"+[i]);
}
Then pulled out the function call from the foreach PHP
foreach ($json_content as $index => $array) {
rest of code here
}
echo '<script type="text/javascript">function();</script>';
if all you need to do is store every $index into a textarea and save it into a java var, then try throwing a while look on every case of echo that you need all variables from...
so for example, you would put a code like this:
while($index = value){
echo $index
}
inside of your #index textarea then grab that textarea's value with java

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>

Send php string to javascript on submit

I want to send a php string to javascript script when I click on submit. I already know how to pass variable with json_encode:
var str1 = <?php echo json_encode($str) ?>;
What I want to know is, how to pass a variable which needs to be selected from a dynamic drop down list and which is in a while loop.
<section class="content">
<form id="admin" action="monitor.php" method="GET">
Servers :<br/>
<select name="category" id="category">
<option value="select">Select...</option>
<?php
$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$result = $redis->keys('*');
$i = 0;
while ($result[$i]!=null)
{
$Addr[$i] = $redis->hget($result[$i], 'Address');
$Port[$i] = $redis->hget($result[$i], 'Port');
$fullAdr[$i] = sprintf ("%s:%s", $Addr[$i], $Port[$i]);
$asdf[$i] = sprintf ("<option value='%s'>%s</option>", $fullAdr[$i], $result[$i]);
echo $asdf[$i];
$i++;
}
?>
</select><br/>
<input type="submit" value="Submit"/>
Now I can't use var str1 = <?php echo json_encode($str) ?>; because I don't know which selection would the user choose.
Each selection contains the IP of a server. I need that IP to pass to a Javascript script when I click on submit.
I am answering it for the future reference, if someone ever encounters the same problem.
I made it work by putting a php on top of the file:
<?php
$JSAddress = $_GET['servers'];
?>
Which I later passed to javascript with:
var str1 = <?php echo json_encode($JSAddress) ?>;
So basically when the user clicks on submit, it sends the request to the php above which stores the value and passes it to javascript.

Assist with javascript functions being contained within a loop (PHP)

I am working on a project where I have divisions stored in mysql database with the "division id" and the "division name";
what I want to have is so that i use php to do a "while" loop and go through all the divisions;
then for each division it creates a button which will trigger a javascript function…
I have done a lot of testing on this so I know certain parts are working…; here is my code:
<p id="id57512">How are you?</p>
<script>
var g_myobj = {};
</script>
<?php
$result_g1 = mysql_query("SELECT * FROM divisions");
while($row = mysql_fetch_array($result_g1, MYSQL_BOTH))
{
$div_id=$row[div_id];
$div_name=$row[div_name];
$button_id="b";
$button_id.=$div_id;
$function_id="f";
$function_id.=$div_id;
?>
<button id=<?php echo $button_id; ?>><?php echo $div_name; ?></button>
<script>
var f_id='<?php echo $function_id; ?>';
var b_id='<?php echo $button_id; ?>';
var div_id='<?php echo $div_id; ?>';
var newFieldName = f_id;
var newFieldValue = function() {document.getElementById("id57512").firstChild.nodeValue=gman_code1(div_id);};
g_myobj[newFieldName] = newFieldValue;
var gman_code1 = function(number) {
var result1 = number*2;
console.log(result1);
return result1;//add return statement
}
//define the behavior
document.getElementById(b_id).addEventListener("click", g_myobj[f_id] , false);
</script>
<?php
}
the function names need to be a variable; but I figured out how to do that by making it an object; and so can access the different functions that way…
I basically tested this all when it was not in a loop; where I manually had it do everything twice (even creating the functions in the object) and it all worked fine…
basically when you click on a button it is supposed to send a number to that "p" container and multiply it by 2
when I did it manually and not in loop i just had it create the object g_myobj first and then just started adding items to the object…
but now that i am doing this in a loop - I felt I could not have the statement that creates the empty object in the loop or it would just keep recreating it; so I went above the loop and had the object created there in its own "script" tags all by itself…
that part may be a problem with this, not sure at all…
another potential problem is that I am not sure if I can do all this in a loop like this
it is a "php loop" and so maybe this just all cannot be done in a loop like that…
What is going on is the first button works but none of the others do…
So, I am hoping someone can advise me on what I am doing wrong on this…
Thanks so much...
If all you are trying to do is send a number to <p> and multiply it by 2, see this one liner function. I assume you are trying to accomplish more than just the multiplying thing otherwise you probably would have just done a simple function like below...
Also, I'm sure you will get lots of comments on it, but you should not be using the mysql_ functions anymore. They are both deprecated and potentially unsafe. You should use mysqli or PDO prepared statements.
On your button, you should probably put quotes around the id="yadayada" instead of id=yadayada. jQuery may be a good option for your js to handle functions or what-have-you.
<p id="id57512">How are you?</p>
<?php
$result_g1 = mysql_query("SELECT * FROM divisions");
while($row = mysql_fetch_array($result_g1, MYSQL_BOTH)) {
$div_id = $row[div_id];
$div_name = $row[div_name];
$button_id = "b$div_id";
$function_id = "f$div_id"; ?>
<button id="<?php echo $button_id; ?>" onClick="MyRadFunction('<?php echo $div_id; ?>')">
<?php echo $div_name; ?></button>
<?php } ?>
<script>
function MyRadFunction(DivId) {
$("#id57512").html(DivId*2);
// var NewNum = $("#id57512").text();
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
When rendering your button, you should wrap the id in quotes, e.g.
<button id='<?php echo $button_id; ?>'><?php echo $div_name; ?></button>

Passing a variable in getElementbyID()

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>

Categories