Sending quoted string to javascript function, then to php - php

I want to send a string containing single and double quotes to a javascript function which then sends it to a php page as a get variable. The code is this (I've tried escaping the quotes in two ways, but none of them work):
<html>
<head>
<script type="text/javascript">
function myFunction (foo) {
window.location = "bar.php?var=" + foo;
}
</script>
</head>
<body>
<a href='javascript:myFunction("text'text"text");'>text'text"text</a><br>
<a href='javascript:myFunction("text&apos;text"text");'>text'text"text</a>
</body>
</html>
The links just don't have any effect.
Thanks!

urlencode * is the correct syntax

try urlencode() the value before echoing it onto the page
<a href='javascript:myFunction(<?php echo urlencode($value); ?>);'><?php echo $value; ?></a>

Try this code:
echo 'text\'text"text<br>';

Related

html code with javascript put to php [duplicate]

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>

using javascript quotes in php code

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>

Interesting output in a simple PHP webpage

Here is a very simple PHP page with one javascript function in it. I am seeing the output differently. I am not able to understand why is it behaving that way.
In the code below, x echoes as 012012, but when I pass it into a javascript function and display it in an innerHTML, it displays differently as 5130 ??!!
Can anyone help ?
<?php
$x= date("mY");
echo $x;
?>
<html>
<head>
<script>
function myfunc1(y)
{
div1 = document.getElementById("mydiv1")
div1.innerHTML = y;
}
</script>
</head>
<body <?php echo "onload='myfunc1(".$x.")'>";?>
<div id="mydiv1" style="background:#efefef;border:1px solid green;height:100px;width:100px;text-align:center">
</div>
</body>
</html>
HTML output
012012<html>
<head>
<script>
function myfunc1(y)
{
div1 = document.getElementById("mydiv1")
div1.innerHTML = y;
}
</script>
</head>
<body onload='myfunc1(012012)'> <div id="mydiv1" style="background:#efefef;border:1px solid green;height:100px;width:100px;text-align:center">
</div>
</body>
</html>
HTML output (screenshot)
Because a number prefixed with a 0 is treated as octal by javascript.
This is happening because 012012 is being treated as an int. But, since it starts with 0, JavaScript treats it as base 8 (octal), and therefore converts it to 5130.
You need to wrap 012012 in quotes, so JavaScript treats it as a string. Also, I suggest only using PHP to echo the value you need, not the entire function call. Makes it slightly easier to debug.
<body onload="myfunc1('<?php echo $x;?>')">
Use Smarty, is a framework template PHP!
PHP code:
<?php
$foo = date('Y');
?>
Simple Print PHP Code
<body onload="myFunctionJS('<?php echo $foo;?>')">
Simple Tags PHP(It is not recommended)
<body onload="myFunctionJS('<?=$foo;?>')">
USE SMARTY TEMPLATE FRAMEWORK
Smarty Template Framework(PHP Code):
<?php
$smarty = new Smarty;
$var = date('Y');
$smarty->assign( 'foo' , $var );
?>
Smarty Template Framework(Template Code):
<body onload="myFunctionJS('{$foo}')">
<body <?php echo "onload='myfunc1(".$x.")'>";?>
should be
<body <?php echo "onload='myfunc1(".$x.")'>";?>>
The body tag is not closed

mix javascript and php

I have a file called: file.php
contained in this file is the following code:
<script type="text/javascript">
//....
var sumJS = 10;
<?php $sumPHP = sumJS ?>
</script>
<?php echo "Sum = " . $sumPHP ?>
How can I assign sumJS for $sumPHP?
If I would like to make this conversely then I would write:
$sumPHP = 10;
<script type="text/javascript">
var sumJS;
sumJS = <?php echo $sumPHP ?>;
alert(sumJS);
</script>
But how can I re-make this for my problem?
Javascript can change the variables of PHP and vice versa.
Here is an example of that.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<?php $aphp=1 ?>
<script "text/javascript">document.write("<?php $aphp=2 ?>")
var ajava=1;</script>
<?php echo "aphp= $aphp"; echo "<br>";
echo "<script \"text/javascript\">ajava=2;</script>"
?>
<script "text/javascript">document.write("ajava= "); document.write(ajava)</script>
</body>
</html>
What if I want to assign a php variable to a java variable and vice versa
The above showed that you can assign values to java in php and vice versa by simply writing out an assignment using echo in php and document.write in java. That is how you assign a value.
Mixing actual variables between php and java is not much more complicated. What you do is write an assignment in the language you need to get the value of a variable from and assign it to a variable in the other language. Here is an example of that.
Assign php to java
<?php echo "<script type='text/javascript'>javasum=$phpsum</script>" ?>
assign java to php can be done in two ways
<script type='text/javascript'>var str="<?php $phpsum=";
str=str+javasum; str=str+" ?>";
document.write(str);
</script>
or more conveniently
javasum=<?php echo $phpsum ?>;
Mixing php and javascript to do things other than variable assignments
Javascript can also be mixed in the phpcode to do a javascript function in the phpcode. Say you wanted to use javascript to highlight text only if a condition is met in the php code. But to do this you need to echo the javascript code section. Also use the escape character, \' to include quotes in a echo command. Here is an example of this
Before you get started be sure php content type is in html. In dreamweaver site editor software, a header to do this is automatically included.
<p><span id="htext">htext</span></p>
<?php
$a=5;
echo "<h3> hello world</h3>";
if ($a==5) {
echo "<script type=\"text/javascript\">";
echo "document.getElementById(\"htext\").style=\"background-color:yellow\"";
echo "</script>";
}
?>
<p>is a=5</p>
<p><?php echo $a ?> </p>
$sumPHP is a server-side value, which will be evaluated on the server. Then the server generates page content and sent it to the client. Then browsers receive the page content and evaluate client-side value sumJS.
So you can never assign sumJS for $sumPHP because $sumPHP is calculated before sumJS.
But can do this to show the page:
<?php echo "Sum = "?><script type="text/javascript">document.write(sumJS);</script>
or rather
<script type="text/javascript">document.write('Sum = ' + sumJS);</script>
You're just missing tags
<?php
$sumPHP = 10;
?>
<script type="text/javascript">
var sumJS;
sumJS = <?php echo $sumPHP ?>;
alert(sumJS);
</script>
demo
Sorry that at the moment I do not have the time to write an example. But I believe that this idea will work. Maybe someone here can do a quick test.
Just create a hidden element with a unique id, say a
span with id="uniqueBufferForCommunicatingBetweenPHPandJS" and style="display:none".
Then, with the JS part of the code, write the result into this span by using
document.getElementById("uniqueBufferForCommunicationBetweenPHPandJS").innerHTML = XXX;
You can even write XXX in the form of JSON.
Afterwards, you can use something in PHP like
$bufferspan = $dom->getElementById('uniqueBufferForCommunicationBetweenPHPandJS');
to get the span, and read its content, probably by using
$avariable = $dom->ownerDocument->saveHTML($avariable);
and then interpret the result stored in $avariable. I am not totally sure about the last PHP code.

Jquery to parse HTML in a string

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>';

Categories