Embed Javascript in php file, syntax - javascript

Using ajax I post data to php file where I have loop with code below.
Part of my code where I can't properly format onclick event:
$result .= '<a href="#" onclick="$("#element").dialog("open");" ></a>';
I tried to escape double quotes with backslash, but no luck. Using backslashes, in console I see: Somehow from nowhere "=" appears, also all backslashes are printed. Code doesn't work.
Could someone help to figure out where I made a mistake in syntax? Thank you.

In your string there are double quotes, followed by content wrapped again in double quotes. The second quotes should be single quotes, but that would terminate the string. So you will have to escape them.
The desired html code should look like this:
to achieve this, you will have to change your PHP code to the e.g. the following:
$result .= '';

When parsing the HTML, the browser will read the onclick="$("#element" part, and infer that attribute onclick equals "$(", because it thought it found the closing double quotes. So, you'll need to escape the double quote character after the $(. Since you're using $result .= 'some_string' (I want to empasize on the single quote being used here), you are unable to escape the double quote character within the single quoted string. Thus, you'll need something like this:
$result .= '<a href="#" onclick="$(\'#element\').dialog(\'open\');" ></a>';
Now, php will translate \' to just ' while rendering, so the final output of the string will be
<a href="#" onclick="$('#element').dialog('open');" ></a>
I hope this helps.

Double quotes should be escaped
$result .= '<a href="#" onclick="$(\"#element\").dialog(\"open\");" ></a>';
Another way is
$result .= `<a href="#" onclick="$('#element').dialog('open');" ></a>`;

Related

PHP - return confirm within PHP issue

could somebody please help me with the below:
echo ('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
I know there is an issue with some " ' " but can't figure this out. I am getting a syntax error just before the 'Are'. The line of code was working as expected before I added the:
onclick="return confirm('Are you sure you want to claim this ticket?');"
Thanks!
If you want to use the same quotes you opened the string with inside the string itself, you should escape it.
For instance:
$var = 'Hello, let's go!';
echo $var;
This code will throw a parse error because this is how PHP sees the code:
) New variable $var.
) Is a string, declared using single quotes '.
) After the opening quote we have 'Hello, let'
) Now PHP expects some kind of valid code operators, like ., and next string or ;, but it gets some characters, which are treated as instructions rather than strings because they are outside the quotes, and
) PHP throws a parse error.
To fix this, you can use the backslash \ a.k.a 'escaping' character.
For example, to fix your problem:
echo
('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
See the baskslashes \ surrounding the single quotes inside the confirm JavaScript function? This tells PHP to treat these quotes as normal characters instead of string start/end declarations. Same thing works for reversal when you use double quotes as string declarators.
For example, when you want to show the actual representation of $ or any characters that have special meaning in a double quoted string, which allows direct insertion of variables (and some other's, like class properties) values you would use the escaping character.
For example:
$apples = 12;
$talk = "I have $apples \$apples. Thanks, now have a backlash! \\!";
echo $talk;
This will output I have 12 $apples. Thanks, now have a backslash! \!
Now, you are not actually required to escape the escaping character (it will show just as well if it does't have anything to escape after it).
Read this: PHP Manual - About Strings
You can also switch your single quotes on the edges of your echo statement with regular quotes, which will allow you to insert the $id variable easier. Then, you just have to escape the quotes around your JavaScript in onClick and switch all the other quotes to single quotes.
echo "<a href='assign.php?id=$id' onclick=\"return confirm('Are you sure you want to claim this ticket?');\" style='text-decoration: none'><font color='FFFFFF'><b>Click here to claim ticket</b></font></a>";
However, there is a better way.
Interpolate PHP into HTML
(Instead of HTML into PHP)
The best way to do this is to write HTML as HTML, and interpolate PHP variables into the HTML. This is best practice as it allows syntax highlighting in IDE's, and looks much cleaner/easier to read.
Just write the entire element as HTML, and then echo the $id variable inside the HTML (instead of writing all of the HTML in a PHP echo statement).
<a href="assign.php?id=<?=$id;?>" onclick="return confirm('Are you sure you want to claim this ticket?');" style="text-decoration: none">
<font color="FFFFFF">
<b>
Click here to claim ticket
</b>
</font>
</a>
With this method, you don't have to worry about escaping quotes, and it will allow you to use regular quotes throughout your entire element.
You need to escape the nested ' by doing \'
echo ('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
Note that all the stuff inside the single quotes is considered as string by the PHP interpreter.
Docs: PHP: Variables - Manual

PHP + Javascript :Use quotes within quotes within quotes

There are a few questions on here on quotes within quotes within quotes, but none have the solution for me.
(I think) I need 'real' quotes within quotes within quotes
My scenario is thus:
<?php echo "<script>text=/"<a onclick=\'myFunction('php-variable')\'>click me</a>/"</script>" ?>
The browser output would be:
<script>text="<a onclick='myFunction('argument')'>click me</a>"</script>
Thanks to a commenter (who didn't post an answer) I have taken the script code out of the <?php ?> and only used it where necessary.
<script>text="<a onclick=\'myFunction('<?php echo $PHP_variable ?>')\'>click me</a>"</script>
The quotes nest as thus
" , /" , '
(Whereas before I was nesting quotes 4 times)
<?php
echo "<script>text=\"<a onclick='myFunction(\\\"argument\\\")'>click me</a>\";document.write(text);</script>";
I've tested it.

escaping single quotes for ajax calls

I have a php page which is called via AJAX. and basically it fetches some value from my database and echos back at table with inputs etc. The problem is when the string it fetches contains quotation marks(actually only single quotes seem to be effected). So on the php page there's something like this:
$value = htmlentities($DB_result->cloumn);
echo'<input type = "button" onClick = "$(\'#something\').val(\''.$value.'\');" />'
so if $value = "hello", no problems but if: $value = 'hello', the page which I'm making the AJAX call from throws up some such error: Syntax Error: unexpected identifier.
so I guess the quotations in $value have not been escaped, which I thought it would with the htmlentities. any Ideas how to solve this much appreciated. Thank you.
The problem is that $value contains single quotes, which interfere with the correct parsing of javascript. from the manual entry for html entities:
all characters which have HTML character entity equivalents are translated into these entities.
this means that your single quotes are not escaped, they are only translated in a way browsers will better understand. You need to use addslashes():
$value = htmlentities(addslashes($DB_result->cloumn));
"'hello'" will become "\'hello\'" which in the browser will look like:
<input type = "button" onClick = "$('#something').val('\'hello\'');" />
which will attribute the string 'hello' (with the single quotes) to the value attribute of $('#something')
Try:
$value = htmlentities($DB_result->cloumn, ENT_QUOTES, "utf-8");
Passing ENT_QUOTES through as a flag will convert both double and single quotes.

Double quotes within php script echo

I have a line of php code that looks like this:
echo "<script>$('#edit_errors').html('<h3><em>Please Correct Errors Before Proceeding</em></h3>')</script>";
I would like to know how to add a font color to the text correctly.
If I do this:
echo "<script>$('#edit_errors').html('<h3><em><font color="red">Please Correct Errors Before Proceeding</font></em></h3>')</script>";
The word "red" is in black text and the compiler throws an error.
If I use single quotes around red, then the text does not show up at all.
Any help would be great.
Thanks
You need to escape ", so it won't be interpreted as end of string. Use \ to escape it:
echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";
Read more: strings and escape sequences
use a HEREDOC, which eliminates any need to swap quote types and/or escape them:
echo <<<EOL
<script>$('#edit_errors').html('<h3><em><font color="red">Please Correct Errors Before Proceeding</font></em></h3>')</script>
EOL;
Just escape your quotes:
echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";
You need to escape the quotes in the string by adding a backslash \ before ".
Like:
"<font color=\"red\">"
if you need to access your variables for an echo statement within your quotes put your variable inside curly brackets
echo "i need to open my lock with its: {$array['key']}";
You can just forgo the quotes for alphanumeric attributes:
echo "<font color=red> XHTML is not a thing anymore. </font>";
echo "<div class=editorial-note> There, I said it. </div>";
Is perfectly valid in HTML, and though still shunned, absolutely en vogue since HTML5.
CAVEATS
It's only valid for mostly alphanumeric and dash combinations.
Never ever do this with user input appended to attributes (those need quoting and htmlspecialchars or some whitelisting).
See also: When the attribute value can remain unquoted in HTML5
In other news: <font> specifically is somewhat outdated however.

Passing an object-string to a javascript-function

I'm trying to pass a string like this:
{"key":["value"],"key2":undefined,"key3":undefined,"key4":undefined,"key5":"value"}
to a javascript-function like this:
<a href="#" onClick="myFunction(myString);">
but can't get the escaping right. Is there a way to pass that object-string to a function or do I need to convert something?
Greetings,
Select0r
try:
var myString = '{"key":["value"],"key2":undefined,"key3":undefined,"key4":undefined,"key5":"value"}';
EDIT:
In light of your recent comment I went back to the browser and tried this (works for me):
<a href="#" onClick="myFunction({'key':['value'],'key2':undefined,'key3':undefined,'key4':undefined,'key5':'value'});">
The change means that it's no longer longer passed as a string but as an object parameter to myFunction.
As Naeem said, you can enclose the string in a single quote. The difference between the single and double quote is this:
single quotes:
Can contain double quotes without stopping string
Cannot contain characters such as break lines
Can contain single quotes via \'
double quotes:
Can contain single quotes without stopping string
Can contain break line and other special characters
Can contain double quotes via \"
I found a solution, Naeem Sarfraz put me on the right track - it's not going to win a beauty contest, but it works:
As I can execute PHP in the context I'm in (but IE6 would ignore Javascript), I did a couple of replacements on single/double quotes with PHP.
$data = stripslashes(unserialize($data));
$data = addcslashes($data, "'");
$data = str_replace('"', "'", $data);
This will strip all slashes, add slashes for single quotes only and finally replace double quotes with single ones.
Now myString is in a state that can be passed to a Javascript function in onclick without quote-conflicts:
<a href="#" onClick="myFunction(<?php print $data; ?>);">
Thanks for your contributions!
If you can generate code just before this <a> element, you can try this:
<script type="text/javascript">
var myObj = {"key":["value"], "key2":undefined, "key3":undefined, "key4":undefined, "key5":"value"};
</script>
<a href="#" onClick="myFunction(myObj)">

Categories

Resources