Get javascript variable value in php - javascript

I need to get javascript variable value in php file.
html example:
UPDATE:
$html = '
<script>
window.runParams.adminSeq="3423423423423";
window.runParams.companyId="2349093284234";
</script>';
Shout I use regex ? regex is very complex to me... any help ?

<?php
$html = '<script>
window.runParams.adminSeq="3423423423423";
window.runParams.companyId="2349093284234";
</script>';
$variables = ["adminSeq", "companyId"];
$counter = 0;
foreach($variables as $variable) {
preg_match_all('/"(.*?)"/', $html, $matches);
${"$variable"} = ($matches[1])[$counter];
$counter++;
}
echo $adminSeq; // Prints out: 3423423423423
echo $companyId; // Prints out: 2349093284234
?>
You can also use GET requests to do this. The link would look like http://localhost/?adminSeq=3423423423423&companyId=2349093284234 then get out these values in PHP with:
<?php
$adminSeq = $_GET["adminSeq"];
$companyId = $_GET["companyId"];
?>

Related

how to pass php variable to javascript?

I am using following code to pass PHP variables to javascript. but it is not working.
function gto(str) {
document.getElementById('goto').action = str;
document.getElementById('ID').value = <?php echo "$userid" ?>;
document.getElementById('name').value = <?php echo "$user_name" ?>;
document.getElementById('gname').value = <?php echo "$usergname" ?>;
document.getElementById('fmname').value = <?php echo "$userfname" ?>;
document.getElementById('img').value = <?php echo "$userimg" ?>;
document.getElementById('email').value = <?php echo "$useremail" ?>;
document.getElementById('goto').submit();
}
Following is the PHP code
<?php
if($_POST["name"] == null)
{
$user_name = 'Annomyous';
}
else{
$user_name = $_POST["name"];
$userid= $_POST["id"];
$usergname= $_POST["gname"];
$userfname= $_POST["fname"];
$userimg= $_POST["img"];
$useremail= $_POST["email"];
}
echo "<p style='color : white'>$user_name";
echo "$userid" ;
echo "$gname";
echo "$fname";
echo "$img";
echo "$email";
echo "$user_name";
echo "$user_name</p>";
$user_name =htmlspecialchars($user_name);
$user_name =str_replace("<script>","", $user_name);
?>
the output is a follows:
ReAlItY TuTs104598758504708047866ReAlItY TuTsReAlItY TuTs//this is php echo output.
JAVASCRIPT OUTPUT:-
function gto(str) {
document .getElementById('goto').action = str;
document.getElementById('ID').value = ;
document.getElementById('name').value = Annomyous;
document.getElementById('gname').value = ;
document.getElementById('fmname').value = ;
document.getElementById('img').value = ;
document.getElementById('email').value = ;
document.getElementById('goto').submit();
}
Function gto is called here:
<button class="w3-btn header-btn" onclick="gto('Contact.php');">Contact Us</button>
I can see in PHP output I am getting all variable output.
but nin juavascript im getting only Annonymous why????
I need to pass post variables to contact us so i am using the form tag and javascript but this is not working Please help me!
Thanks in Advance
values from php to js can be passed in many ways, here's one of them
try to pass the php values when calling the js function, like this:-
<button onclick="gto('Contact.php','<?php echo $userid;?>','<?php echo $username;?>');">Contact Us</button>
and then get values on js function like this:-
function gto(str,userid,username) {
document .getElementById('goto').action = str;
document.getElementById('ID').value = userid;
document.getElementById('name').value =username;
}
that's it, now use the values in js as your wish
Uh, found another issue. The js is in smart quotes, which won't work... "`" is invalid. use "'".
Also, w3schools can't handle php in their editor, so it's no use.
Example for POST requests: https://www.w3schools.com/code/tryit.asp?filename=FQSA8MJYGJ47
Hope this helps.

php variable to javascript with json_encode

I know this topic was already discussed a few times but I can't seem to find what I'm doing wrong.
What I'm trying to do:
The user types in a number and by clicking on the button creates a table with that number of columns.
Heres the php:
<?php
$twig = require_once('bootstrap.php');
$hostname = 'localhost';
$username = 'root';
$password = '';
$conn = new PDO("mysql:host=$hostname;dbname=mydb", $username, $password);
echo $twig->render('index.html', array());
$numOfRows = 1;
if(isset($_POST['button'])){
$numOfRows = $_POST['num_input'];
}
html/javascript:
<html>
<head>
<script>
function insertRows(){
var numOfRows = <?php echo json_encode($numOfRows) ?>;
var out = "<table><tr><th>test</th>";
for (i = 0; i < numOfRows; i++){
out += "<th>test</th>";
}
out += "</tr></table>";
document.getElementById("table").innerHTML = out;
}
</script>
</head>
<body>
<form action="index.php" method="post">
<textarea id="num_input" name ="num_input"></textarea>
<button type="button" name="button" onclick="insertRows()"> Go </button>
</form>
<p id="table"></p>
</body>
</html>
Theres no error or anything since I'm not using a IDE, just doing it in vim but the error is that is just doesn't happen. If i change "numOfRows" in the for loop to a number it works, so I'm pretty sure the json_encode is the problem.
Thanks!
EDIT:
Just to test it, I used a string variable $str = "test"; the php file, and instead of using the for loop, I just edited javascript to
var str = <?php echo json_encode($str); ?>;
alert(str);
and I also tried
var str = <?php echo $str; ?>;
alert(str);
but nothing works.
json_encode is not necessary in this case.
Simply replace
var numOfRows = <?php echo json_encode($numOfRows); ?>;
with
var numOfRows = <?php echo (int)$numOfRows; ?>;
Edit: You are missing a ; on the
<?php echo json_encode($numOfRows) ?>
Should be
<?php echo json_encode($numOfRows);?>
And in these cases, if would be good to check the server log, this will automaticly make you better at finding these mistakes yourself.
You are mixing up ints and strings. The database will in PHP always return strings and the way you are using the variable as an int in a for loop.
The following change i believe would achieve the right result.
$numOfRows = intval($_POST['num_input']);
Where you use PHP's conversion to integer function there is at a global level.
You did not forget any $. JS does not need $ for variables.
As far as your json_encode is concerned, if you are just passing an integer from PHP to JS, there is no need to json_encode. Just pass the variable to JS as <?=$numOfRows?> in the JS source.

How to get text from html and javascript tags and functions

Hello every one i want to get text from this code
$content = '<span class="version_host">
<script type="text/javascript">
document.writeln('streamin.to');
</script>
</span>';
I want to get the text between ('streamin.to') streamin.to
I am using strip_tags() function of php
$test = strip_tags($content);
echo $test;
output:
document.writeln('streamin.to');
please help me i want the text streamin.to only.
One way is to Use str_replace
<?php
$content = "<span class='version_host'>
<script type='text/javascript'>
document.writeln('streamin.to');
</script></span>";
$test = strip_tags($content);
$test1 = str_replace("');","",str_replace("document.writeln('","",$test));
echo $test1;
?>
OR USING preg_match
<?php
$content = "<span class='version_host'>
<script type='text/javascript'>
document.writeln('streamin.to');
</script></span>";
$test = strip_tags($content);
$data = preg_match("/\'([^\']*?)\'/", $test, $matches);
echo $matches[1];
Or Using explode as stated by #Rene Pot
<?php
$content = "<span class='version_host'>
<script type='text/javascript'>
document.writeln('streamin.to');
</script></span>";
$test = strip_tags($content);
$array = explode("'",$test);
$string = $array[1];
echo $string;
?>
Hope this helps you
The following should provide what you need.
$content = "<span class='version_host'>
<script type='text/javascript'>
document.writeln('streamin.to');
</script>
</span>";
$test = strip_tags($content);
$array = explode("'", $test);
echo $array[1];
With explode you split the string "document.writeln('streamin.to')" by ' delimiter, and get an array of 3 elements.
What strip_tags() does is getting rid of any <> tags in a String, so document.writeln('streamin.to'); remains.
Now, you only want to get the part between the single quotes, so best would be to use regular expressions (learn more on regExOne.com)
output = "document.writeln('streamin.to');".match(/'([^']+)'/);
Then output[1] will contain what you're looking for.
edit:
If you want to achieve the same using php, try
preg_match("/'([^']+)'/", "document.writeln('streamin.to');", $output);
In that case $output[1] will contain what you're looking for

How to retrieve $_SESSION value in a JavaScript/HTML

I have this working script yet when I change it to retrieve(supposedly) the value inside $_SESSION["username"], it doesn't retrieve anything. The whole page is saved as .php as I am using some codes that uses PHP.
Code:
echo "<script type=text/javascript>";
echo "var hidden = false;";
echo "function actiondb1() {";
echo "if(!hidden) {";
echo "document.getElementById(\'clickdb1\').style.visibility = \'hidden\';";
echo "document.getElementById(\'db1\').style.visibility = \'visible\';";
echo "document.getElementById(\'db1\').disabled = false;";
echo "document.getElementById(\'db1\').value =".$_SESSION["username"];.";";
echo "}";
echo "}";
echo "</script>";
How can I make the script to properly retrieve the data inside $_SESSION["username"];?
Observe that, for instance, if the value of $_SESSION["username"] is John, your echo will be generating this result:
document.getElementById('db1').value = John;
But John is supposed to be a string and should be wrapped in quotation marks, otherwise JavaScript will understand it as a variable name (which value will be probably undefined).
As Havenard mentioned, this line is missing Javascript single quotes to properly denote a string variable:
echo "document.getElementById(\'db1\').value ='".$_SESSION["username"];."';";
However, you really shouldn't print JS out with PHP if you can help it. Though iatboy's answer answer won't ultimately fix your bug, it is a much cleaner way of doing things.
?>
<script type=text/javascript>;
var hidden = false;
function actiondb1() {
if(!hidden) {
document.getElementById('clickdb1').style.visibility = 'hidden';
document.getElementById('db1').style.visibility = 'visible';
document.getElementById('db1').disabled = false;
document.getElementById('db1').value ='<?php echo $_SESSION["username"];?>';
}
}
</script>;
<?php
Did you start session in this page?If you didn't,use the follow code to start session.
session_start();
Then change your code to
echo "<script type=text/javascript>";
echo "var hidden = false;\n";
echo "function actiondb1() {\n";
echo "alert('".$_SESSION['username']."')\n"; //test code
echo "if(!hidden) {\n";
echo "document.getElementById('clickdb1').style.visibility = 'hidden';\n";
echo "document.getElementById('db1').style.visibility = 'visible';\n";
echo "document.getElementById('db1').disabled = false;\n";
echo "document.getElementById('db1').value ='".$_SESSION["username"]."';\n";
echo "}\n";
echo "}\n";
echo "</script>";
it will be ok.

.replace() not working inside a jQuery function

I don't understand why replace() function doesn't work into my jQuery function:
jQuery(document).ready(function($){
var amount_min = <?php if($_GET['amount_min']) echo $_GET['amount_min']; else echo '0'; ?>;
var amount_min = amount_min.replace(/[^\d]/g, "");
$('input[name=amount]').val(amount_min);
});
Whatever input I give (for example "100ab" or "10.000") it doesn't replace it with "100" or "10000".
How to do?
You forgot to put double-quotes.
var amount_min = "<?php if($_GET['amount_min']) echo $_GET['amount_min']; else echo 0; ?>";
Because, replace works in Strings.
UPDATE #1
If for any religious reason you don't want to wrap the PHP in double quotes then output them along with the number.
var amount_min = <?php echo '"' . ($_GET['amount_min'] ? $_GET['amount_min'] : 0) . '"'; ?>;
UPDATE #2
Compulsory validation you can use:
var amount_min = <?php echo '"' . (int)($_GET['amount_min']) . '"'; ?>;
can you please try this:
$(document).ready(function(){
var amount_min = "<?php if($_GET['amount_min']){ echo $_GET['amount_min'];}else{ echo '0';} ?>";
console.log("original-> "+amount_min);
var amount_min = amount_min.replace(/\D/g,'');
console.log("replaced-> "+amount_min);
});
Your PHP code is outputting a number:
var amount_min = 100;
Since you're expecting a string, wrap it in quotes:
var amount_min = "<?php if($_GET['amount_min']) echo $_GET['amount_min']; else echo '0'; ?>";
I haven't touched PHP in years, but I think you could simplify your code a little:
var amount_min = "<?php echo($_GET['amount_min'] || '0'); ?>";
Also, why don't you just fetch the GET parameter with JavaScript?
You don't need the .replace() code (it also only works on strings); PHP can already do the proper conversion for you:
$(function() {
var amount_min = <?php echo isset($_GET['amount_min']) ? (int)$_GET['amount_min'] : 0; ?>;
$('input[name=amount]').val(amount_min);
});
You could also use filtering for this:
<?php echo filter_input(INPUT_GET, 'amount_min', FILTER_VALIDATE_INT, array('options' => array('default' => 0))); ?>
Note that filter_input would not accept a value like 100abc, so use wisely.
If you still want to use strings safely in JavaScript you should use json_encode().
Btw, any answer that involves an unmodified echo of a request variable from PHP inside JavaScript code is wrong and can cause XSS attacks! You have been warned.
Update
The regular expression based replacement can also be done in PHP:
var amount_min = <?php echo (int)preg_replace('/\D+/', '', isset($_GET['amount_min']) ? $_GET['amount_min'] : 0); ?>;
Since all non-digits are removed, you can safely apply the (int) cast.

Categories

Resources