PHP generated JavaScript onClick, with PHP array, quotes problem - javascript

echo '<a onClick="articleDeleteConfirm("'.
$row["title_$lang"].'","'.$_GET["editPage"]).'">';
The main problem is with: $row["title_$lang"], I have to use $lang variable inside. " and ' just not enough.

The problem you describe actually has nothing to do with your PHP variables, those are all being output as expected. The problem is that you need to escape the " inside of the <a> and you've misplaced a ).
Your original would output:
<a onClick="articleDeleteConfirm("value1","value2">
That is not valid HTML (even the highlighter dislikes it). Now, notice the \'s in the following (and that the paren was moved into the string).
echo '<a onClick="articleDeleteConfirm(\''
.$row["title_".$lang."].'\',\''.$_GET["editPage"].'\')">';
The escaped version outputs:
<a onClick="articleDeleteConfirm('value1','value2')">
It uses single quotes inside of double quotes to provide easy to read (and valid) html. Now, you have another issue with your code.
Any time you output a $_REQUEST variable to the browser, you risk something called cross-site-scripting. Someone could put JavaScript into $_GET["editPage"] and it would smell bad. The easy way to avoid it? Use htmlentities($_GET["editPage"])

I had same problem too, I don't know exactly why but I had syntax error no matter what I did, So I tried this and got answer.
The problem is that you're using a double quotation to open onClick and again you're using another double quotation to open an string.
Use this and you'll get answer.
echo '<a onClick="articleDeleteConfirm('.char(39).$row["title_$lang"].char(39).','.char(39).$_GET["editPage"]).char(39).'>';

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

Passing PHP variables as strings to javascript

Somehow my php function, which creates a button, which calls a javascript function, does not pass the php variables as strings.
function addTableEntry($id, $name)
{
echo('<tr>
<td>'.$id.'</td>
<td>'.$name.'</td>
<td>Manage group
</tr>');
}
addTableEntry(1,"livingroom");
The function activateGroupSettingsOverlay() always gets called with (1, livingroom) whenever it is clicked and i get an error "livingroom is undefined".
How can i pass $name as a String? I tried to put quotes around it (like this: '.$id.',"'.$name.'", but that did not work.
You have to "escape" quotes inside a string if you want them to persist:
echo '..... onClick="activateGroupSettingsOverlay('.$id.',\''.$name.'\')"....'
The important thing are the backslashes before the (single) quotes.
The reason it wasn't working is because you were not including quotes in the javascript.
While other answers "fix" the issue they don't really explain it, to be clear this line
<td>Manage group
Is output like this
<td>Manage group
As is, the livingroom does not have quotes and so javascirpt is treating it as a variable, hence the undefined error. To fix it you want it to look like this when output.
<td>Manage group
Modifying this line is all you have to change
<td>Manage group
Adding the single quotes \' with escaping.
Personally for things like this I like to use what is called a HEREDOC or NEWDOC
<<<HTML HTML; and <<<'HTML' HTML; respective. HEREDOC is like using a " and new doc is like using ' in that you cannot use php variables within a NEWDOC but you can within the HEREDOC if you enclose them in { } braces. Because of this we'll want to use a HEREDOC so we can use php variables in the output.
function addTableEntry($id, $name)
{
echo <<<HTML
<tr>
<td>'.$id.'</td>
<td>'.$name.'</td>
<td>Manage group
</tr>
HTML;
}
addTableEntry(1,"livingroom");
http://php.net/manual/en/language.types.string.php - scroll down to where it says HEREDOC
The advantage to doing this is that you don't have to escape the single quotes, which makes it way more readable IMO. The trick with HEREDOC, or NEWDOC, is the ending HTML; has to start a new line and can be the only thing on that line, no leading or trailing spaces, or it won't work properly..
For this case it is probably simple enough to get away with how you are doing it, but if you needed to use concatenation in javascript, the quotes would become a hassle. For example say you wanted to add a html image tag using javascript with a javascirpt variable for the image name, but use php to get the server host name( html and variables in javascript ).
echo '
var foo = "image.jpb";
$(body).html( \'<img src="'.$_SERVER['HTTP_HOST'].'\'+foo+\'" />\' );
';
This quickly becomes unmanageable because ( not even sure if I have that right, anyway ). Compare how much cleaner this is, because you are not wasting the quotes in php....
echo <<<HTML
var foo = "image.jpb";
$(body).html( '<img src="{$_SERVER['HTTP_HOST']}'+foo+'" />' );
HTML;
Please try with this code:-
function addTableEntry($id, $name)
{
echo("<tr>
<td>".$id."</td>
<td>".$name."</td>
<td>Manage group
</tr>");
}
addTableEntry(1,"livingroom");
Change
onClick="activateGroupSettingsOverlay('.$id.','.$name.')"
to
onClick="activateGroupSettingsOverlay('.$id.',"'.$name.'")"
#chandresh_cool was kind of right, you have to "force" the quotes
onClick="activateGroupSettingsOverlay('.$id.',\''.$name.'\')"

Pass image url from variable to html in javascript

In my script, text(message.image) returns a dynamic URL path of an image. What would be the correct statement in a javascript?
This fails:
$('<div/>').'<img src=\"'.text(message.image).'\">'.appendTo($('#msgDiv'));
The real answer is:
$('<div><img src="'+message.image+'"/></div>').appendTo($('#msgDiv'));
You have a couple syntactic errata in your code snippet:
You can't access a property with a string like you do.
Concatenation of strings is not with a dot but with a plus.
You are trying to execute text() on a string, not on the div.
I think you're missing (),+,append method and escaping " incorrectly, try with this:
$('<div/>').append('<img src="' + text(message.image) + '"/>').appendTo($('#msgDiv'));
Hope this helps,
I think you have a problem because you're using (double)quote badly
You escape the double quote but you're using simplequote. Try that :
$('<div/>').'<img src=\''.text(message.image).'\'>'.appendTo($('#msgDiv'));
And are you sure concerning the syntax $('').'SOME HTML CODE' ?
You are missing ( and ) there.
Also, you dont need to escape double quotes since you are using single quotes outside.
Try this:
$('<div/>').('<img src="'+text(message.image)+'">').appendTo($('#msgDiv'));

javascript syntax for passing variables to function

I have a JavaScript hyperlink that is not passing variable to function, undoubtedly due to syntax. Can someone please spot error.
jsfiddle: http://jsfiddle.net/kSVVX/
js
function follow(id){
alert(id);
}
html
<a href='javascript:void(0);' onclick= 'follow('1');'><img src='images/test.gif' border=0 alt='follow'></a>
Note: The reason that I am using all apostrophes is that this link is actually getting echoed from php where a long string is enclosed in quote marks (as certain things in the string must be in apostrophes.) I have a feeling this is source of problem, but have not succeeded in solving it by changing punctuation around.
Thanks for any suggestions.
You are using ' characters to delimit your JavaScript string and the HTML attribute value it is embedded in.
This results in:
onclick= 'follow('
Either:
Avoid intrinsic event attributes (which you should be doing anyway, unobtrusive JavaScript is recommended).
Use different characters to delimit the attribute value (onclick="follow('1');") or string (onclick= 'follow("1");')
Use HTML entities to include the quote mark you are using in the data for the attribute value (onclick= 'follow('1');')

Using JavaScript single and double quotes for href's

I am having problem with escaping the single and double quotes inside the hrefs JavaScript function.
I have this JavaScript code inside href. It's like -
click this
Now, since double quotes inside double quote is not valid, I need to escape the inner double quotes for it to be treated as part of the string -
so, I need to do this -
click this
The problem is, even the above code is not working. The JavaScript code is getting truncated at -- myFunc(
I tried with the single quote variation too - but even that doesn't seem to work (meaning that if I have a single quote inside my string literal then the code gets truncated).
This is what I did with a single quote:
<a href = 'javascript:myFunc("fileDir/fileName.doc" , true)'> click this </a>
This works, but if I have a single quote inside the string then the code gets truncated in the same way as that of double quotes one.
Using backslashes to escape quotes is how it works in JavaScript, but you're not actually writing JavaScript code there: you're writing HTML. You can do it by using the HTML escaping method: character entities.
" // "
' // '
For example:
...
In case anyone needs to escape some thing like this:
<a href="www.google.com/search?q="how+to+escape+quotes+in+href""</a>
You can use ASCII code for double quotes %22:
<a href="www.google.com/search?q=%22how+to+escape+quotes+in+href%22"</a>
It is especially useful if you pass the link to JavaScript from PHP
As a general best practice, use double-quotes in HTML and single-quotes in JavaScript. That will solve most of your problems. If you need a single-quote in a JavaScript string, you can just escape it using \' - and you probably shouldn't be nesting literal strings any deeper than that.
As noted elsewhere, HTML entities are a possibility if the code is embedded in HTML. But you'll still have to deal with escaping quotes in strings in your JavaScript source files, so it's best to just have a consistent strategy for dealing with JavaScript.
If you are following this strategy and end up with a double-quote embedded in your JavaScript embedded in your HTML, just use the HTML entity ".
Normally, this kind of code is working without problems:
Click this
With this code, do you have any problem?

Categories

Resources