How pass variable php in javascript in function? - javascript

so i want try pass variable php to function javascipt where variables is
<?php $code1=""; ?>
and for function is
<script type="text/javascript">
var $code1 = $(this);
$txt=new Array();
var $code1 = <?php echo $code1("code1"); ?>;
$(function(){
$('#go').on('click',function(){
console.log($('form').serialize());
})
$('body').on('keydown','.last',function(){
$('.last').removeClass('last');
$('#go','body').before(
'<table><tr><td><input class="last" type="text" id="code1" name="code'+(Number($(this).attr('name').match(/[0-9]+/g))+1)+'" value=" SHOULD BE HERE "></td></tr></table>');
})
})
</script>
should be value is ="$code1" so i try value= "<?php echo $code1; ?>" but it's cant can help me pls?

json_encode() is what you want, but all the quotes and what not are handled for you by the JSON-encoding. Don't add more quotes. Also, it's easiest if in your JavaScript, you assign stuff to their own variables.
var data = <?php echo json_encode($data); ?>;
Also, I recommend that you don't simply concatenate data into HTML like this. Otherwise, you're lacking escaping for HTML which can cause ambiguity and injection problems.
$('<input>').val(data);

Related

Failing to embed php in javascript

Im trying to give a javascript variable a value from php, this way:
<script type="text/javascript">
var id = <?php echo json_encode( $_GET['id']); ?>;
window.alert('Javascript still works');
The probem is once include the line: var id = <?php echo json_encode( $_GET['id']); ?>;
My javascript breaks any ideas on the way around this?

Pass a php variable to a jQuery function

I have searched and tried several different methods to pass a php $variable to a jQuery function. I can pass a string simply by using myfunction("Hello");. But if I try myfunction(); or myfunction($variable); with or without quotes it fails to run.
function wholesection(val) {
$("#whole-section").slideUp("fast", function () {
});
$('#label-cemetery').text("Section*");
$('#poc').val(val);
}
The above works if I send a literal string enclosed in double quotes, using:
<?php
echo '<script>',
'wholesection("Hello");',
'</script>'
;
?>
</head>
<body>
<?php
$variable = "Hello";
echo '<script>',
'wholesection(' . $variable . ');',
'</script>'
;
?>
Or other similar variants do not work.
'wholesection($variable);',
'wholesection("$variable");',
Suppose your $variable has value "Hello".
Then this code:
echo 'wholesection('.$variable.');',
is rendrered in html like
wholesection(Hello);
See? You're passing Hello to a function. Not "Hello" but Hello.
And Hello is considered a javascript variable. I bet you don't have it.
So, the fix is - add quotes:
echo 'wholesection("'.$variable.'");',
which will be rendered as:
wholesection("Hello");
You can pass it by echoing your php varriable in the script
try below code :
<?php
$variable = "Hello";
?>
<script type="text/javascript">
var simple = '<?php echo $variable; ?>';
</script>
<?php
$variable = "Hello";
if(true){
?>
<script>
wholesection("<?php echo $variable?>");
</script>
<?
}
?>

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 call a php variable in .js file? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 years ago.
I want to use a php variable in .js file. Is this possible that we can call a php variable in .js file.
what I have done for this problem
I have .php file where i created var
$domainname = "wwww.google.com ";
In second file .php
<?php header("Content-type: application/javascript"); ?>
<script>
var DomainName = <?php echo $GLOBALS['SettingDomainName'];?>
</script>
and finally I want to call this var in js
<script src="public_https/test.js"></script>
alert(DomainName);
I got this message :
SyntaxError: syntax error
<script src="public_https/test.js"></script>
Use json_encode function which returns JSON representation of a variable which can be used inside JavaScript as-is:
<?php
$domainname = "www.google.com";
?>
<script>
var DomainName = <?php echo json_encode($domainname); ?>;
</script>
Note: no quotes. This function works for all types of variable: string, integer, float, boolean, null and etc.
<script>
var DomainName = "<?php echo $GLOBALS['SettingDomainName'];?>";
</script>
What about we hide your variable in a hidden box using php
$domainname = "wwww.google.com ";
<input type="hidden" value=" <?php echo "$domainname"; ?>" id="mydomain">
Then we fetch it using js or jquery
<script>
var domain=$('#mydomain').val();
</script>
<input type="hidden" id="domain_name" value="<?php echo $GLOBALS['SettingDomainName']; ?>">
JsFile:
var DomainName= document.getElementById('domain_name');

PHP -file_exists() Function? [duplicate]

How I can set the JavaScript variable strUser from PHP?
I am using the following code:
<script>
function val()
{
var e = document.getElementById("ali");
var strUser = e.options[e.selectedIndex].text;
}
</script>
brand<select id="ali" onChange="val()">
<?php
$brand=modsearchkhodroHelper::retrieve();
foreach($brand as $item)
{
?>
<option value="<?php echo $item['brand']?>" selected="<?php $id=$item['brand']?>">
<?php echo $item['brand']?>
</option>
<?php
}
echo "</select>";
?>
If you want to set the variable when the page loads, you could use something like this in the PHP code:
<script type="text/javascript">var strUser = <?php echo json_encode($someVariable); ?>;</script>
Just make sure to remove the later variable declaration from the JavaScript.
If you want to set the variable after the page loads, you'll have to use an AJAX call to ge the value from the server.
Use Cookie
in your javascript
<script type="text/javascript">
document.cookie = "cookieName=cookieValue";
</script>
in your php
<?php
$phpVar = $_COOKIE['cookieName'];
echo $phpVar;
?>

Categories

Resources