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>
Related
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'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>';
lets imagine a form editor, it can edit available values. If the data contains " character (double quote) it "destroys" HTML code. I meant, lets check the code: so I generate HTML:
onclick="var a = prompt('New value: ', '<?php echo addslashes($rec[$i]); ?>'); if (a != null)....
and it results in
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....
and this makes JS work impossible, so that it ruins the code. With single qoute ' it works OK. mysql real escape does the same.
How to escape any string so that it won't ruin javascript?
json_encode looked OK, but I must be doing something wrong, its still bad: heres a screenshot how Firefox sees it - it inserts a "bad" double quote! The value is just a simple number:
http://img402.imageshack.us/img402/5577/aaaahf.gif
and I did used:
('Ird be az új nevet:', <?php echo json_encode($rec['NAME']); ?>); if (a) {
The value of the onclick attribute should be escaped like any other HTML attribute, using htmlspecialchars(). Actual Javascript strings inside the code should be encoded using json_encode(). For example:
<?php
$message = 'Some \' problematic \\ chars " ...';
$jscode = 'alert('.json_encode($message).');';
echo '<a onclick="' . htmlspecialchars($jscode) . '">Click me</a>';
That being said... onclick (or any other event) attributes are so 2005. Do yourself a favor and separate your javascript code from your html code, preferably to external file, and attach the events using DOM functions (or jQuery, which wraps it up nicely)
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....
Your problem is highlighted in bold.
You can't quote a variable declaration
you shouldn't need to escape the double quote once this is removed since it is within single quotes.
Should look like this -
onclick="newFunc();"
<script>
function newFunc() {
var a = prompt('New value: ', 'aaaa"aaa');
if (a != null) { v....
}
</script>
...onclick="new_func();"...
<script>
function new_func() {
var a = prompt('new value:','<?php code; ?>');
if (a) { <!--javascript code--> } else { <!--javascript code--> }
}
</script>
I'm really just re-wording what #Marshall House says here, but:
In HTML, a double quote (") will always end an attribute, regardless of a backslash - so it sees: onclick="var a = prompt('New value: ', 'aaaa\". The solution that #Marshall offers is to separate your code out into a function. This way you can print escaped PHP into it without a problem.
E.g.:
<script>
// This is a function, wrapping your code to be called onclick.
function doOnClickStuff() {
// You should no longer need to escape your string. E.g.:
//var a = prompt('new value:','<?php echo $rec[$i]; ?>');
// Although the following could be safer
var a = prompt('new value:',<?php json_encode($rec[$i]); ?>);
if (a) { <!--javascript code--> }
else { <!--javascript code--> }
}
</script>
<someelement onclick="doOnClickStuff();"> <!-- this calls the javascript function doOnClickStuff, defined above -->
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 have problem and I tried click link then it doesn't work to open link using target: name of iFrame. i dont want use href because im going make show/hide div.
Javascript:
<script type="text/javascript">
<!--//
function godirect(url, targetname)
{
document.getElementById(targetname).src = url;
//frame[targetname].location.href = url;
}
//-->
</script>
in HTML and PHP:
$a=0;
echo 'Click Me!';
echo '<iframe class="iframe_url" id="iframe_url'.$a.'"></iframe>';
How about
<script type="text/javascript">
function godirect(url, targetname) {
window.frames[targetname].location = url;
//OR
//window.open(url,targetname);
return false;
}
</script>
<?PHP
$a=0;
?>
Click Me!
<iframe class="iframe_url" name="iframe_url<? echo $a; ?>" id="iframe_url<? echo $a; ?>"></iframe>
You have to quote strings in JavaScript. You are trying to get the id of the element by passing in a variable which you haven't defined.
You are also using the same quote characters to delimit your HTML attribute value as you are using to delimit your JS strings.
To use the approach you are using, while making the minimum number of fixes to make it work:
echo 'Click Me!';
Using JS for this is a very silly idea in the first place though, and your implementation fails to have any kind of fallback for when JS is not available (which is odd, since you are taking steps to stop browsers which don't recognise the script element from rendering the JS as content text).
You can do this with plain HTML:
<a href="http://www.google.com"
target="iframe_url<?php echo htmlspecialchars($a); ?>">
Click Me!
</a>
i dont want use href because im going make show/hide div.
You can do that as well as having a normal, functioning link. Build on things that work.
Try this:
echo 'Click Me!';
echo '<iframe class=\"iframe_url\" id=\"iframe_url'.$a.'\"></iframe>';
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).