How to store HTML-Markup in the ID-Attribute? - javascript

I need to show for every link, dynamically some text with Java-Script (jQuery). The problem is that the text is also formatted as HTML, so this causes some problems in the later view.
Now I am storing it in the ID-attribute, this works, but only without embedded HTML in it.
<?php
...
$desc = '<p style="color: red">some <span>data</span></p>';
echo '' . $key . '';
?>
Ajax-requests are not allowed. Is there a simple way to reach this goal?

The id attribute is one of the least appropriate places for this (must be unique, cannot contain all characters). Use a data- attribute (introduced in HTML5 but also works in old browsers and without using a HTML5 doctype) instead:
<a href="#" data-desc="....">
If you are using jQuery you can access it via .data('desc'), in plain JavaScript the most portable way is using .getAttribute('data-desc'). If you do not need to support older browsers, you can access the value via the .dataset.desc property.
In any case, you need to ensure that nothing breaks when inserting dynamic data in the attribute. Use htmlspecialchars() for this purpose:
$desc = '<p style="color: red">some <span>data</span></p>';
echo '' . $key . '';

The other comments are absolutely right. Don't do this. It isn't appropriate to put anything but an identifier of some kind in the id attribute.
That being said, I figured I would let you know why your code is failing. You need to use htmlspecialchars() on your data before you try to use it as you intend. That way, HTML won't be interpreted as HTML... all of the HTML entities will get converted for, so your attribute value is interpreted as text. < becomes <, > becomes > and so on. If you later pull the value out (with jQuery or whatever), you will get the text as intended.

Related

How do I write inline Javascript inside a HTML attribute, inside a PHP string?

I want to open a modal by changing the display property of an element upon clicking a different element. How would I write the following HTML attribute:
onclick="document.getElementById(edit).style.display="inline-block"
inside a PHP string?
For PHP, you should use a backslash to escape the double quotes inside a double-quote string. E.g.
echo "onclick=\"document.getElementById(edit).style.display='inline-block'\"";
Notice the single quotes for the inline JavaScript. This makes it easier than using only double quotes, as otherwise you'd have something like:
echo "onclick=\"document.getElementById(edit).style.display=\\"inline-block\\"\"";
Edit: I also just noticed your getElementById has no quotes around it, you're passing a variable. So, for more fun:
echo "onclick=\"document.getElementById(\\"edit\\").style.display=\\"inline-block\\"\"";
or simply:
echo "onclick='document.getElementById(\"edit\").style.display=\"inline-block\"'";
...And this is why inlining everything is a bad idea. Define your onClick handlers outside of the element, in a <script> block.
You should read up on your string syntax.
See: http://php.net/manual/en/language.types.string.php#language.types.string.syntax
For Javascript, it's much the same - see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Escaping_characters

generate HTML from a set of jQuery objects?

I am trying to modify an HTML string (things like adding class to one of its children). In my code I have to used a container as a midway to ouput $html as a string. Does jQuery provide any function to do this?
html = "<p>title</p><div><ul class='www'></ul>something</div>";
$html = $(html);
$html.filter('div').find('ul').addClass('xxx');
container = $('<div></div>');
html = container.html($html)[0].innerHTML; //output "<p>title</p><div><ul class='www xxx'></ul>something</div>"
Nope.
There is no escape to interacting with the DOM (this is creating or selecting an existing element), the best you can try is to document.write your string but you'll need to scape the HTML so it doesn't gets interpreted as HTML but text. Notice that document.write only works before the document finishes loading.
I don't know your needs but I can't think of a good use case for this, your jQuery should be better for most cases.

Truncating A php String for given Width in Pixels

I want to truncate a given string taken from MySQL database through PHP to fit within given pixels. Most of the solutions I found were based on number of characters. But I specifically want it according to pixel length.(I don't want to use monospace font)
I found out that $('#idName').width() can be used in JavaScript for fitting. And that works fine with strings written in HTML simply. But here is the deal. My string is a variable stored in PHP, I need JavaScript to get width in pixels and I need to have that string in a span (in HTML) with specific id name.
So, I have tried to make it work using all three of them- PHP, HTML and JavaScript. Below is my code.
<?php
$len=100;
?>
<span id='d' style="display:none;"><?php echo substr($details,0,$len) ?></span>
<script>
var len=370;
while($('#d').width()>len){
<?php
$len=$len-1;
echo "<span id='d' style='display:none;'>" . substr($details,0,$len) . "</span>";
?>
}
<?php echo substr($details,0,$len); ?>
</script>
So I take my string's first 100 letters and put them in a span with id d. Then in JavaScript, I get its width and check in while loop. I run while loop (keep decreasing $len) until the pixel length of the substring is within desired width and keep redifining that substring in span with same id. Then I print that substring.
Could someone please change the code to make it work or suggest a better method? I am newbie in this, so please make it as simple as you can.
As far as I understand from your question, you are trying to hide an overflow when the string is longer than container given?
I would rather suggest using overflow:hidden; white-space:nowrap; and maybe some text-overflow:ellipsis; to make "..." effect just before the end of container. But you have to remember, that fonts render differently through most browsers and operating systems, so the user experience might be different on Windows than on Mac.
That probably won't work. JS and PHP can't be mixed like that. The while loop is useless.
One solution that came to my mind is that you can first get the PHP string, through ajax, and then display it according to the width using JS.

Ways to pass information from PHP to JQUERY?

I'm having a hard time figuring out what is the best way to transfer information from PHP to Jquery. I know putting PHP in Javascript is a really bad alternative (my JS and PHP files are seperated anyway), so what I usually do is print the info with PHP in the HTML with a input type hidden and retrieve the info in JQuery using the element.text() or .val() or any other method, but I feel this is kind of noobish. Is there a better way?
I recommend never using a server-side language to build JavaScript. Instead, keep your data in HTML (model), your styles in CSS (view), and your interactions in JS (controller).
When you need to pass data to JavaScript, make good use of attributes and templates.
When it comes to passing data via attributes, you can go a long way with just using native attributes.
In this example, it is quite apparent that the link will open a modal, and the [href] attribute is used to point to where the modal lives:
Open modal
<div id="modal">lorem ipsum</div>
When you can't fit data within native attributes, you should make use of [data-*] attributes.
In this example, [data-tooltip] is being used to store a rich-text tooltip.
<div data-tooltip="<p>lorem ipsum</p>">...</div>
Even more importantly, jQuery automatically grabs and casts all [data-*] attributes on a DOM node when .data() is called on the node.
<div id="example"
data-foo="bar"
data-fizz="true"
data-max="100"
data-options="{"lorem":"ipsum"}">
...
</div>
<script>
$('#example').data();
/*
{
foo: 'bar',
fizz: true,
max: 100
options: {
lorem: 'ipsum'
}
*/
</script>
The thing to watch out for is JSON encoding within HTML encoding. jQuery makes it very straight-forward to get the data out of the DOM node without needing to worry about decoding, but in PHP you need to make sure that you json_encode data before calling htmlentities:
<div data-example="<?= htmlentities(json_encode($someArray)) ?>">...</div>
In some instances you may want to make use of jQuery's .attr() method.
For large amounts of data, such as an HTML template string, you can use <script> tags with a template mime type (such as type="text/x-jquery-tmpl"):
<script id="template-example" type="text/x-jquery-tmpl">
<h1>${title}</h1>
<p>${body}</p>
</script>
Or you can use the HTML5 <template> element:
<template id="template-example">
<h1>${title}</h1>
<p>${body}</p>
</template>
You can then access the HTML contents of the element run it through whatever your favorite flavor of string templating happens to be.
You can simply echo PHP variables into Javascript variables for your jQuery to use like this:
<?php
$stringVar = "hi";
$numVar = 1.5;
?>
<script>
var stringVar = "<?php echo $stringVar; ?>";
var numVar = <?php echo $numVar; ?>;
</script>
This can be used for practically any data type as long as you convert it correctly upon echoing it (oftentimes json_encode() is enough for complex structures such as arrays and objects).
Also note that this way will only work if your jQuery code is included after these variables have been defined.
The other way is to look into using AJAX, but if these are static variables that don't need to change within the lifetime of the page then I would go with the method above.

Best way to store JQuery variables?

I just want to get some thoughts on storing variables for JQuery's use.
Example
Here JQuery would use the the value of the video_id hidden input, and then voteup the video by the video_id.
<form class='voteup' action='' method='post'>
<input type="hidden" name='video_id' value='<?php echo $video_id; ?>' />
<input type='submit' value='Vote Up' />
</form>
Note: This is just an example.
But what if I want a link to do the same thing. Where would I store the video_id?
Obviously, I could store the video_id in the class attribute, but I don't think that this is the best way, especially if I needed to send more than one variable.
Any ideas on this?
I must mention that I'm only looking for XHTML valid ways.
You can use the jQuery data method to attach arbitrary data to an element. In your case, if I've understood what you're trying to do correctly, you probably want to do something like this:
$(document).ready(function() {
$("#yourLink").data("video_id", "<?php echo $video_id; ?>");
});
As you are looking for valid XHTML solutions, you can't use the HTML5 data-* attributes. If that was the case, you could add the attribute value directly on the element (as you've done with the value attribute in your example).
The data method does not require a corresponding data-* attribute to be present on the element, so this will still allow you to write valid XHTML.
If you digg HTML5 you should go for the data attribute.
http://ejohn.org/blog/html-5-data-attributes/
In an HTML 5 page, you can use "data-" attributes for things like that:
<img src='http://placekitten.com/100/100' data-video-id='whatever'>
Then, from jQuery:
$('img').click(function() {
var video = $(this).data('video-id'); // 'videoId' also works here
});
If you're (tragically) stuck with strict XHTML, well, you're stuck. For an <a> tag you could possibly use the "rel" attribute I guess. In general "class" is probably in fact the thing to do. The convention I've used for name-value pairs in the "class" is to separate them with a colon and then extract them via regex:
<sometag class='whatever videoId:video22 something'>
and then:
$('sometag').click(function() {
var videoId = this.className.replace(/videoId:(\S*)/, '$1');
// ...
});
Perhaps use the rel attribute, and grab it in jQuery using the .attr() method.
var myVar = $('#link_id').attr('rel');
http://api.jquery.com/attr/

Categories