How can I use a php variable in javascript - javascript

If I have created a variable in php, say $test, how can I set a variable in javascript, say var test, to be equal to it.
I have already tried var test = <?php $test ?>

I guess
var test = <?php echo json_encode($test) ?>
The naive way var test = '<?php echo ($test) ?>' will fail if $test contains quotes or newlines, let alone is not of the string type (e.g. array, object)

var test = '<?php echo $test; ?>'

try like this :
var test = '<?php echo $test ?>';

var test = '<?php echo $test; ?>';
Or using shorthand echos, like this:
var test = '<?= test;?>';

var test = <?php echo json_encode($test); ?>

You can use
<pre>
var test = '<?php echo $test?>';
</pre>
below the definition of $test.

Change
var test = <?php $test ?>
to
var test = <?php echo $test; ?>

You are missing two things:
var test = <?php $test ?>
1) Echo statement.
2) Single Quotes around PHP snipplet.
So, the corrected code should be:
var test = "<?php echo $test ?>";

Within your page where you want your PHP to output to type:
var MyJavascriptVariable = <?php echo $myPHPVariable; ?>
Advise NOT to use short tags () as this can be disabled by webhosts and may break your code.

Related

phpcoding special characters

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"}")>

Unable to print PHP variable using JS

I understand that this question has been asked a lot of of times, but the solutions posted there don't seem to work for me. I have a code as follows:
<script>
var JSvar = "<?php echo $phpVar ?>";
document.write(JSvar);
</script>
<?php
$phpVar="jajha";
?>
I actually want to pass a PHP variable to a JS function, but I wanted to try if printing the variable works first. Please help me out.
instead of
<script>
var JSvar = "<?php echo $phpVar ?>";
document.write(JSvar);
</script>
<?php
$phpVar="jajha";
?>
try
<?php
$phpVar="jajha";
?>
<script>
var JSvar = "<?php echo $phpVar ?>";
document.write(JSvar);
</script>

using php _GET within javascript function

I have some javascript embedded into an html file that I am running in a browswer.
document.getElementById('home-search-text-inp').value = <?php echo htmlspecialchars($_GET['search_for']); ?>;
Why does this not fill the textbox?
Note that:
document.getElementById('home-search-text-inp').value = "hi";
puts "hi" into the textbox and:
<?php echo htmlspecialchars($_GET['search_for']); ?>
writes text just fine.
Thanks in advance
You're missing quotes around your string value:
document.getElementById('home-search-text-inp').value = <?php echo htmlspecialchars($_GET['search_for']); ?>;
^^^^ ^^^^
HERE HERE
should be:
document.getElementById('home-search-text-inp').value = "<?php echo htmlspecialchars($_GET['search_for']); ?>";

How to alert PHP value in JavaScript?

<script type="text/javascript">
var jvalue = 'this is javascript value';
<?php
$abc = "<script>document.write(jvalue)</script>" ?>
</script>
<?php echo 'php_'.$abc; ?>
<script type="text/javascript">
var test = "<?php echo $abc; ?>";
</script>
<?php
echo '<script language="javascript">';
echo 'alert(test)';
echo '</script>';
?>
How to alert test variable, which contains PHP value?
I would like to get the PHP value in javascript, for further execution in my project.
try this code
<?php
echo '<script language="javascript">alert("'.$test.'"); </script>';
?>
this is updated code for you using javascript and PHP
<?php
$user = "rebel";
echo '<script> var name = "'.$user.'";
alert(name);</script>';
?>
This is the third code for you if this does not work then you have other problem
<?php
$abc= "Hello";
?>
<script type="text/javascript">
var test="<?php echo $abc; ?>";
</script>
<?php
echo '<script language="javascript">';
echo 'alert(test)';
echo '</script>';
?>
why are you assigning the variable to a javascript variable and then echoing that? sounds like extra work to me...
echo 'alert("' . $abc . '");';
Your code is not so clear, i think you want something like this:
<?php
$test = "hi there!";
echo '<script type="text/javascript">';
echo 'alert("'.$test.'")';
echo '</script>';
?>
var test="<?php echo $abc; ?>"
<script language="javascript">alert(test); </script>
If you want to alert the value of $abc, you need to escape the slash in the following line with a backslash, like this.
<?php $abc = "<script>document.write(jvalue)<\/script>" ?>
You also need to remove this line (or escape the < and the > in $abc). If you don't, the script tags will mess up the rendered html code.
<?php echo 'php_'.$abc; ?>

Run PHP echoed Javascript

I am just getting into the world of PHP, Javascript and HTML and would like some help from the community regarding the following code. Basically I want to pass variables plucked from a ODBC_connection by PHP into textboxes. Lines 1-3 were for me to test to get the box to update which it does but anything echoed by PHP does not run. I am completely new to this so I realize I must be missing something trivial.
I welcome any suggestions or comments about what I can do to fix this or what I can do better in general.
Thank you.
<script type='text/javascript'>
document.getElementById('modeltxt').value = "test2";
</script>
<?php
echo "<script type='text/javascript'>";
echo "document.getElementById('modeltxt').value =\"TEST3\";";
echo "document.getElementById('customertxt').value = $customer;";
echo "document.getElementById('endusertxt').value = $enduser;";
echo "document.getElementById(dongletxt').value = $dongle;";
echo "document.getElementById('shipdatetxt').value = $shipdate;";
echo "document.getElementById('chasistypetxt').value = $chasistype;";
echo "document.getElementById('chasisnumbertxt').value = $chasisnumber;";
echo "document.getElementById('opsystxt').value = $opsys;";
echo "document.getElementById('dvd1txt').value = $dvd1;";
echo "document.getElementById('dvd2txt').value = $dvd2;";
echo "document.getElementById('storagetxt').value = $storage;";
echo "document.getElementById('nodrivetxt').value = $nodrive;";
echo "document.getElementById('drivesizetxt').value = $drivesize;";
echo "document.getElementById('interface1txt').value = $interface1;";
echo "document.getElementById('interface2txt').value = $interface2;";
echo "document.getElementById('interface3txt').value = $interface3;";
echo "document.getElementById('interface4txt').value = $interface4;";
echo "document.getElementById('interface5txt').value = $interface5;";
echo "document.getElementById('interface6txt').value = $interface6;";
echo "document.getElementById('commentstxt').value = $comments;";
echo "document.getElementById('warrantyexptxt').value = $warrantyexp;";
echo "document.getElementById('extendedwarrantytxt').value = $extwarexp;";
echo "document.getElementById('onsitetxt').value = $onsite;";
echo "document.getElementById('sqlversiontxt').value = $sqlversion;";
echo "<\script>";
You can create dynamics JS using the below
Define Content-Type on the top of your .js.php file:
<?
header('Content-Type: application/javascript');
// Write your php code
?>
and call the js file like this ..
<script type="application/javascript" src="JS_PATH/name-of-file.js.php"></script>
and if you want to use inline php values, you can write like this
<script type="application/javascript">
document.getElementById('modeltxt').value = "<?php echo $dummy_value ?>";
</script>
No need to do this. You can simply use javascript inside php as below :-
As you mention in your question
Basically I want to pass variables plucked from a ODBC_connection by PHP into textboxes.
<?php
// Php block of code
?>
<script type="text/javscript">
document.getElementById('modeltxt').value = "TEST3";
document.getElementById('customertxt').value = "<?php echo $customer;?>";
......
....
...
</script>
<?php
// Another block of code
?>

Categories