Can I please have some help in using a PHP variable in some Javascript code.
I am wanting to pass a value to a Javascript function that is stored in a PHP variable.
Here is my code:
$UpdateText="updateReTotal(Tills,'pos_cash','{$till->till_id}');updateVariance('{$till->till_id}')";
echo '<script type="text/javascript">'
, 'testFunctionForUpdateTotal(.$UpdateText.);'
, '</script>';
Thanks in advance.
$UpdateText="updateReTotal(Tills,'pos_cash','{$till->till_id}');updateVariance('{$till->till_id}')";
echo '<script type="text/javascript">'
. 'testFunctionForUpdateTotal('.$UpdateText.');'
. '</script>';
Your code would have worked if you were using double quotes (except for the two dots beside your variable, plus you need to escape the other double quotes), like this:
echo "<script type=\"text/javascript\">
testFunctionForUpdateTotal($UpdateText)
</script>";
But this does not work with single quotes.
<script language='javascript'>
function show(j)
{
alert(j);
}
</script>
<?php
$v = "a";
echo "<div onclick=\"show('".$v."',);return false;\">CLICK</div>";
?>
Related
I am new to PHP. I need to output the following JavaScript with PHP. This is my code:
<html>
<body>
<?php
echo "<script type="text/javascript">";
echo "document.write("Hello World!")";
echo "</script>";
?>
</body>
</html>
But it's showing the error:
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /var/www/html/workbench/person/script.php on line 4
Can anyone please help? I also need some simple tutorials on how to use PHP, HTML and JavaScript for an application.
You should escape the JavaScript string delimiters inside the PHP string. You're using double quotes for both PHP and JavaScript strings. Try like this instead:
<html>
<body>
<?php
// Here, we use single quotes for PHP and double quotes for JavaScript
echo '<script type="text/javascript">';
echo 'document.write("Hello World!")';
echo '</script>';
?>
</body>
</html>
You have to escape quotes on both JavaScript and PHP when the string delimiter are the same as the quotes:
echo "\""; // escape is done using a backslash
echo '\'';
Same in JavaScript:
alert("\""); // escape is done using a backslash
alert(echo '\'');
But because it's very hard to read a string with such escape sequences, it is better to combine single with double quotes, as needed:
echo '"';
echo "'";
The error you get if because you need to escape the quotes (like other answers said).
To avoid that, you can use an alternative syntax for you strings declarations, called "Heredoc"
With this syntax, you can declare a long string, even containing single-quotes and/or double-quotes, whithout having to escape thoses ; it will make your Javascript code easier to write, modify, and understand -- which is always a good thing.
As an example, your code could become :
$str = <<<MY_MARKER
<script type="text/javascript">
document.write("Hello World!");
</script>
MY_MARKER;
echo $str;
Note that with Heredoc syntax (as with string delimited by double-quotes), variables are interpolated.
Another option is to do like this:
<html>
<body>
<?php
//...php code...
?>
<script type="text/javascript">
document.write("Hello World!");
</script>
<?php
//....php code...
?>
</body>
</html>
and if you want to use PHP inside your JavaScript, do like this:
<html>
<body>
<?php
$text = "Hello World!";
?>
<script type="text/javascript">
document.write("<?php echo $text ?>");
</script>
<?php
//....php code...
?>
</body>
</html>
Hope this can help.
An easier way is to use the heredoc syntax of PHP. An example:
<?php
echo <<<EOF
<script type="text/javascript">
document.write("Hello World!");
</script>
EOF;
?>
You need to escape your quotes.
You can do this:
echo "<script type=\"text/javascript\">";
or this:
echo "<script type='text/javascript'>";
or this:
echo '<script type="text/javascript">';
Or just stay out of php
<script type="text/javascript">
You need to escape the double quotes like this:
echo "<script type=\"text/javascript\">";
echo "document.write(\"Hello World!\")";
echo "</script>";
or use single quotes inside the double quotes instead, like this:
echo "<script type='text/javascript'>";
echo "document.write('Hello World!')";
echo "</script>";
or the other way around, like this:
echo '<script type="text/javascript">';
echo 'document.write("Hello World!")';
echo '</script>';
Also, checkout the PHP Manual for more info on Strings.
Also, why would you want to print JavaScript using PHP? I feel like there's something wrong with your design.
The following solution should work quite well for what you are trying to do.
The JavaScript block is placed very late in the document so you don't have to
worry about elements not existing.
You are setting a PHP variable at the top of the script and outputting just
the value of the variable within the JavaScript block.
This way, you don't have to worry about escaping double-quotes or HEREDOCS
(which is the recommended method if you REALLY must go there).
Javascript Embedding Example
<div id="helloContainer"><div>
<script type="text/javascript">
document.getElementById('helloContainer').innerHTML = '<?= $greeting; ?>';
</script>
You want to do this:
<html>
<body>
<?php
print '
<script type="text/javascript">
document.write("Hello World!")
</script>
';
?>
</body>
</html>
instead you could easily do it this way :
<html>
<body>
<script type="text/javascript">
<?php
$myVar = "hello";
?>
document.write("<?php echo $myVar ?>");
</script>
</body>
You are using " instead of ' It is mixing up php syntax with javascript. PHP is going to print javascript with echo function, but it is taking the js codes as wrong php syntax. so try this,
<html>
<body>
<?php
echo "<script type='text/javascript'>";
echo "document.write('Hello World!')";
echo "</script>";
?>
</body>
</html>
<?php
echo '<script type="text/javascript">document.write(\'Hello world\');</script>';
?>
Try This:
<html>
<body>
<?php
echo "<script type="text/javascript">";
echo "document.write("Hello World!");";
echo "</script>";
?>
</body>
</html>
Oh boy! I cant get this to work. Any ideas on what the heck I'm doing wrong? Here's the code.
I'm trying to echo the script but use a php function to get the directory of the js file!!
Any help would be appreicated!!
echo '<script src="<?php get_some_function();?> . /js/main.js"></script>';
I've tried dif scenerios with escaping but cant get this to output correctly.
Since you're already in the PHP context, you can simply concatenate the strings, like so:
echo '<script src="' . get_some_function() . '/js/main.js"></script>';
Using sprintf() looks more cleaner, though:
echo sprintf('<script src="%s/js/main.js"></script>', get_some_function());
Instead of opening another script tag inside the string, concat the string and echo. The <?php within your string will not be evaluated.
echo '<script src="'. get_some_function() . '/js/main.js"></script>';
Simple string concatenation:
echo '<script src="' . get_some_function() . '/js/main.js"></script>';
Don't forget to properly escape the output of your function!
try doing this:
echo '<script src="'.get_some_function().' /js/main.js"></script>';
or this:
$value = get_some_function();
echo '<script src="'.$value.' /js/main.js"></script>';
Remember that any variable echoed in single quotes ( ' ' ), the value of that variable will be not printed, and if a variable is echoed in double quotes ( " " ) it will be printed.
Similar is true for returned data from a function stored in a varaible. If you are using single quotes, then every php code (variable, or a method call of a class) should be concatenated using dot operator ( . , :P ) . If you are using double quotes, then no need to use . .
Like in all above answers, they have used . to append the php function call, your code may be fine as below also (not tested by me, so you will need to do adjustment) :
$src = get_some_function();
echo "<script src=$src/js/main.js></script>";
But please note that it is a best practice to use single quotes for any kind of html etc echoed in php code, because HTML attributes are using double quotes.
Hope this will help...
i'm having some trouble using javasript in php code, I'm confused in using double quotes and single quotes.
echo 'Delete';
or how to do the above code in php ?.
Thanks
use this code
echo 'Delete';
you have to escape the quotes.
http://viper-7.com/F6uI0L
You need to escape the quotes with htmlspecialchars (for HTML):
echo '<a href="..." onclick="return confirm('
.htmlspecialchars('"Are you sure"') . '">Delete</a>';
(alternatively you could just write ")
...but don't do that. Use JS event registration:
document.getElementById('a-id').addEventListener('click', function (e) {
if (!confirm("Are you sure...")) {
e.preventDefault();
}
});
Do that in JS file. It requires that the <a> have an ID (you could also do it with a host of other selectors, but ID is the simplest).
Change like following
echo "Delete";
Why don't you put the HTML outside of PHP tags? For example you could do:
...
?>
Delete
<?php
...
Another way to echo HTML is:
echo <<<HTML
Delete
HTML
Error in confirm("Are you sure you want to delete?")"> you need to escape double quote.
You need to call the javascript function using php echo
echo 'href_link';
...but you have to use JS function
<html><head><script type="text/javascript">
function fun()
{
if(confirm('are you sure')) return TRUE;
else return FALSE;
}
</script>
</head>
<body></body>
</html>
I tried searching the related posts, and having a hard time figuring out how to fix my query - I'm pretty close, any help is much appreciated (new to Jquery).
I program in PHP, and trying to pull either the HREF value from a tag, or the text. Either will work.
I basically have my HTML code in a string, might contain multiple tags, and would like to load the text of the tags into either a PHP array or variable (right now just trying to ALERT the results, I can dump it later).
My PHP Code:
<?php
$info = '<li><strong>I want this text</strong>';
echo '<script type="text/javascript">';
echo '$("document").ready( function () {';
echo 'alert($("a", $("' . $info . '")).html());';
echo '});';
echo '</script>';
?>
The above doesn't alert anything. Putting in
echo 'alert("yes")';
does work, so I'm guessing there's something basic wrong with my syntax, but 4 hours later still unable to find it! :)
Thanks in advance.
You aren't Javascript-escaping the quotes in your string.
Your code creates Javascript that looks like
$("<li>...<a href="http..."...")
The quotes in the attribute end the Javascript string, creating a syntax error.
You need to call json_encode.
SLaks has the rest of your problem. But also, it's not:
$("document").ready();
It's:
$(document).ready();
The former is a selector for a tag named <document>.
This should work the way you want it to:
<?php
$info = '<li><strong>I want this text</strong></li>';
?>
<script type="text/javascript">
$(document).ready( function () {
alert($("a", $("<?php echo $info; ?>")).html());
});
</script>
You are not closing your li Tag
$info = '<li><strong>I want this text</strong>';
should be
$info = '<li><strong>I want this text</strong></li>';
You should escape info. It's breaking because you've got double quotes inside of double quotes:
$info = addslashes($info);
or
$info = json_encode($info);
or just
$info = str_replace('"', '\\"');
Try to save the HTML is a JS variable first, then use it. Also, heredocs are your friend.
<?php
$info = '<li><strong>I want this text</strong></li>';
echo <<<END
<script type="text/javascript">
$(function(){
var HTML = '$info';
alert($('a', $(HTML)).html());
});
</script>
END;
?>
echo '<script type="text/javascript">
$(document).ready( function () {
var info = \''.$info.'\';
$("a").html(info);
alert(info);
});
</script>';
I am trying to echo this jquery function, with php. basically if the script detects a field of a form is not filled in then it will echo this and make the input text box turn red.
It works fine when it is not being echo'd.
echo('
<script type="text/javascript">
$(document).ready(function() {
$(\'input\').animate({backgroundColor:\"#F00\"},200);
});
</script>
');
any ideas?
I don't think you have to escape your quotes when the string is within single quotes. PHP won't parse the string, it will be output literally.
You're over-doing it on the string escape. To keep it simple, just use single quotes around the echoed string, and use double quotes inside it. Something like:
echo('
<script type="text/javascript">
$(document).ready(function() {
$("input").animate({backgroundColor: "#F00"}, 200);
});
</script>
');
When you're echoing stuff, there are indeed some cases when you need to escape the quotes, but most of the times you can simply get away with it by using different types of quotes. For example, I'll never get it why people still do something like:
echo "<input type=\"text\" name=\"username\">";
as opposed to
echo '<input type="text" name="username">';
which makes your life a whole lot easier when you have to modify it.
Hope this helps !
You shouldn't use \" there, just "
Furthermore: a hex-color-value is no numeric value you can use for animate() .
By this, the error is fixed by removing the backslashes from the doublequotes, but your animation wouldn't show any effect.
i didnt test it, but try that:
$nl = "\n";
echo '<script type="text/javascript">'.$nl;
echo ' $(document).ready(function() {'.$nl;
echo ' $("input").animate({backgroundColor:"#F00"},200);'.$nl;
echo ' });'.$nl;
echo '</script>'.$nl;
the $nl="\n" is only for linebreak (I prefer to use singlequotes in echos, so php didn't have to parse the content - just echo out).