Creating dynamic elements with Javascript event using echo in PHP? - php

It's simple if the code is written in Javascript (between the <script> and </script>, but I'm encountering a problem like this (render dynamic content using echo in PHP):
echo "<label onclick='showContent(\"".$content."\")'>Click me</label>"
and I also tried this:
echo '<label onclick="showContent("'.$content.'")">Click me</label>'
The problem is that $content can contain many characters like " (double quote), ' (single quote)... Generally, it contains HTML code.
If it is a normal sentence, the code above will work well, it renders a label of 'Click me' and I can click it to run the function showContent(), but if it contains HTML code, it can render the label however I can't run the function showContent() when I click on it. I think there is some problem with quotes here. I tried replacing all the single and double quotes in $content with " or \" and ' or \' but it still doesn't work, even in some cases, the label of 'Click me' can't be rendered properly, instead of that it shows me almost the code behind.
I'm really stuck at this (already for hours), please give me a solution. Your help would be highly appreciated!
Thanks!

Try this:
echo '<label onclick="showContent('.$content.')">Click me</label>'

Related

PHP echo returning blank value

So I am trying to link using data I got from a function but it keeps giving me a blank value for ID. Here's my code for what I'm trying to print
<h3 style="text-align: center;">Seller: <?php $sellername =
getNameFromListingID(); $id = getIDByUsername($sellername); echo "".$sellername."";?></h3>
The functions work properly, I have tried printing both of them and it works. They're in a file called getinfo.php, which I have
Include 'getinfo.php';
At the top of my document.
The link with the name works but I always get seller.php?id=, with no value after. Any clue as to why?
You're ending the href attribute too early.
<a href=\"seller.php?id=".$id."\">
This will put the $id inside the href attribute, where it belongs.
Use single quotes in PHP, it's a good practice to get into, and it's also slightly (a teeny tiny bit) faster for PHP to process. Why? Because, when you use double quotes, you're telling PHP that your string contains variables that may need to be evaluated.
So in truth, you don't even need the quotes around variables here.
echo "$sellername";
But doing it like this would be following a best practice.
And now you don't need to escape \" double quotes that HTML uses.
echo ''.$sellername.'';
Caution: It's also a very good idea to escape special characters in anything you're outputting into HTML markup. That avoids the potential for an XSS vulnerability. See: htmlspecialchars()
echo ''.htmlspecialchars($sellername).'';

Displaying a new image/window with PHP variables when you rollover an image

When I first asked how to achieve something like this: http://backpack.tf/ (Mouse over on any item) I got pointed to JQuery.
Then I tried achieving the same by using; http://jqueryui.com/tooltip/
I was able to create the window but I couldn't figure out how to set it up so that it displays $object->level or some other variables like that.
I than tried; http://stevenbenner.github.io/jquery-powertip/
Again I was able to create the tooltip. And it lets you create tooltips using the data-powertip="" tag. Like this;
Some Link</div>
But still, I can't place my variables in there. I'm using echo to print this into HTML body and all the quotation marks start to be a problem.
Please help me with this. How to create eye-candy tables like when you hover on an item in this page: http://backpack.tf/
you may need to escape your quotes.
For instance,(assuming your tooltip plugin works by showing some data from an attribute), try this:
Make your html element use double quotes for attribute like(assuming it uses data-tooltip for tooltip data, you need to change that to whatever your plugin uses.)
<img data-tooltip="your data will go here" ... >
^ ^
Used double quotes for attribute
you would be echoing that from php using single quotes because you have double quotes there, like:
echo '<img data-tooltip="your data will go here" ... >';
Now your problem is you need to put html inside that attribute, fortunately you can use single quotes for html attributes too but unfortunately you also used single quotes to echo from php.
What you need to do is escaping the inner quotes! like:
echo '<img data-tooltip="<span class=\'some-css-class\'>Some Text '.$somePhpVariable.'</span>" ....>';
you escape your quotes with backslash. You will see that stackoverflow code highlighter will highlight the above code properly.

Appending a string to the end of a URL in a variable in PHP

So I have this code for a youtube link in a wordpress widget
$title = "<h5 class='widget_title sidebar_widget_title'><a
href='http://www.youtube.com/user/".$options['username']."'
target='_blank'>".$options['title']."</a></h5>";
So I'm trying to append
?sub_confirmation=1
after my youtube user name so that a subscribe confirmation comes up but wow I have tried everything and am just not a good enough coder yet.
You just insert the query string parameter to the string.
$title = "<h5 class='widget_title sidebar_widget_title'><a href='http://www.youtube.com/user/".$options['username']."?sub_confirmation=1' target='_blank'>".$options['title']."</a></h5>";
The reason this is possibly confusing to you is because the author of the code you're changing used " to tell PHP that the next sequence of characters form a string, and ' to tell HTML that this is the value for the href attribute (like <a href='youtube.com'>...</a>). This works because HTML supports both " and ', and it saves you the hassle of having to escape quotes.
Personally, I'd rather use ' for PHP-strings and regular " for HTML, but that's a matter of taste.

jQuery load function escapes data

I have a strange problem with the load function from jQuery. It escapes HTML content that jQuery gets back from the load function. I load HTML output from a PHP file into a div. I use this function:
function XXX(file,divName,functionToCall)
{
$("#" + divName).load(file,null,function()
{
functionToCall();
});
};
The HTML output of the PHP file:
<div onClick="xxx(0,'xxx')" id="xxx"></div>
Jquery converts it into:
<div onClick="xxx(0,\'xxx\')" id="xxx"></div>
Because of this convention I can't use the onClick function, it isn't valid any more. I can't figure out what I 'm doing wrong, does some one know what causes this problem and how to solve this in a good way? I already read other related question on Stack overflow, but I couldn't find an answer how to avoid escaping.
I guess your problem isn't in a PHP block. Here are some rules you need to follow:
For PHP use these rules:
When to escape the char ' :
When you want to use ' in a ' ' block. For example: echo 'test: \' this workes ';
When you don't need to escape the char ' :
When you want to use ' in a “ ” block. For example: echo “test: '
this workes “;
For HTML use these rules:
If you aren’t in a PHP block, then you don't need to escape data. The data you wrote here will directly be outputted. When you want to make a onClick, just use this template: onClick”functionName('stringValue');”
Maybe it's because of the editor:
Some editors will give \' an other color, don't let the colors distract you. It doesn't mean it's correct! Use a file editor with less features ( like notepad ) and open the PHP file where you were talking about. Check again if there are no \'s on places where they shouldn't be.
The problem isn't JQuery in this case. Trust me, look at the PHP file. Did you maybe escaped data outside a PHP block?
This has something to do with you PHP implementation not javascript. When PHP outputs your html it's set to escape quotes.

Escaping quote, both " and '

I am trying my best to work this out and it is driving me crazy, I am hoping that I can use either preg_replace or ereg_replace for this.
Basically I am putting out string of text which is taken from a news article, I am taking the first 100 characters rounded to the closest end of word, the problem occurs if a " or ' appears in the 100 characters string and no closing " or ' is present, this then causes my PHP code to fail. So I need to write some kind of replace code so that all " and ' will be replaced with \" and \' so they are escaped and don't affect my PHP.
Update
I cannot correct anything to do with database insertion as I am dealing with a very old archive of data which I cannot process and re-enter into the database so I'm stuck with what I have got there.
This is the code I have:
$text = preg_replace('/\s+?(\S+)?$/', '',substr($text, 0, 100));
echo '<div style="color: #8197cd;" >'.$text.'...</div>';
So that takes my text, shortens it and puts it to the nearest word.
Then I am trying to do something along the lines of:
$text = preg_replace("\"","\"",$text);
$text = preg_replace("\'","\'",$text);
But preg_replace is not a strong point of mine so that is completely wrong!
the problem occurs if a " or ' appears in the 100 characters string and no closing " or ' is present, this then causes my PHP code to fail.
You're trying to fix a problem that shouldn't be there in the first place - most likely unescaped input in a mySQL query. You need to fix that instead (it's also a security problem).
Show the code that breaks, I'm sure someone will be able to point out what needs to be done.
Something seems to be missing from your question. You should consider posting the code that is having a problem.
Having quotes inside a variable you are echoing out is not going to fail. The only thing I could imagine causing an error would be if you were using some sort of template system or code that was taking the string and using it to do an eval() somewhere, but that would be a very poor system.
If you are inserting the string into a database, then you would need to escape those characters, as mentioned by SiteSafeNL.
If an eval is the source of the problem, then htmlentities which he also suggested would fix it.
Added based on latest additions to the question
Please try this:
echo '<div style="color: #8197cd;" >'. htmlentities($text) . '...</div>';
And the preg_replaces are not useful, so simply omit that code.
Don't you need anything like mysql_real_escape_string or htmlentities?

Categories