Generate Unique ID in two places - javascript

I need to generate a unique ID via js or PHP. Obviously this is pretty easy, but the part I can't figure out is that I need to generate a unique id for a <p> element, and then reference that unique id in some inline js below.
Here's the code to make this more clear:
<p id="UNIQUE-ID" class="toolbox"><a class="tooltip" onmouseover="tooltip.pop(this, '##UNIQUE-ID');"></a>
Basically, in both places where it says "UNIQUE-ID", I need an identical unique id generated. There will be an unknown number of these kind of <p> and <a> pairs generated dynamically.
Any help is greatly appreciated.

You've said that the <p> and <a> pairs are generated dynamically, and also asked for a unique ID "...via js or PHP..." So I'm going to assume the dynamic generation is via PHP, in some kind of loop.
If so, just remember the value in a variable in your loop and output it in the two required locations, e.g.:
<?php
while (someCondition) {
$id = /* ...generate the ID...*/;
?>
<p id="<?=$id?>" class="toolbox"><a class="tooltip" onmouseover="tooltip.pop(this, '##<?=$id?>');"></a>
<?php
}
?>
(Obviously that's using shorttags, which many people recommend against. But it gets the idea across. If you don't use shorttags, you can easily change that to use echo instead.)

I am just giving the structure.Just change it according to your requirement
<?php
for($i=0;condition;$i++)
{
?>
<p id="par_<?php echo $i;?>" <a id="id_<?php echo $i;?>" href=""></a>
<?php
}
?>

Related

get data-value with variable value

I have a data-value in my php code that is used in several places, for example:
<a class="dropdown-item" data-value="<?= $i ?>"></a>
<a class="dropdown-item" data-value="<?= $k ?>"></a>
And now I need to use one of these values ​​in the script
getAttribute('data-value')
But I can’t just use data-value, since it will be relevant to everything that I have, I only need to use this data-value="<?= $k ?>"
How can I specify a value with this variable in the script?
since you want to get the data-value of a specific element with the $k variable, your best bet is giving an id to that specific element and selecting it by id:
HTML
<a id="element_with_k" class="dropdown-item" data-value="<?= $k ?>"></a>
JS
const elementWithK = document.getElementById('element_with_k');
elementWithK.dataset.value // "the content of $k"
In case thete are multiple elements that you want to select then you add an extra class to those elements, query all the elements that have the extra class , loop through them and get each element's value.
Hope this helps, cheers!

What is the functional difference between these two snippets of code?

What is the functional difference between these two snippets of code
<!--?php include('json-ld.php'); ?--><script type="application/ld+json">// <![CDATA[
<?php echo json_encode($payload); ?>
// ]]></script>
and
<?php include('json-ld.php'); ?><script type="application/ld+json">
<?php echo json_encode($payload); ?>
</script>
My objective is to apply a JSON-LD file (containing schema.org structured data) to my WordPress site. The first code is taken from this page, and purports to do what I need. But I can't understand why the author would post a snippet with so many comments. From what I understand about HTML and JS comments, the code appears to be functionally equivalent to the bottom code. I am posting here to assure myself that I am not misunderstanding something about this syntax.
Perhaps there is a security purpose for using the commented code? If so, I would be interested in practicing best practices in terms of security.
Thanks.
CDATA stands for Character Data and it means that the data in between these strings includes data that could be interpreted as XML markup, but should not be. This is so that html tags and such can be used without it breaking the xml code - each html tag would be represented as a child-node to the xml. By using the CDATA "comment" you are telling the xml to consider the html tags as a string value, not a child-node.
Regarding the first line: <!--?php include('json-ld.php'); ?--> This isn't including the file - this may be a typo on the original authors' part. If your code works without it, it is probably safe to remove; otherwise, fix it ;)
From what I see, it's purely so that potential output of <?php include('json-ld.php'); ?> are not treated as HTML.
Since most of the time there is no output in <?php include('json-ld.php'); ?> , <!-- <?php include('json-ld.php'); ?> --> just do <!----> . But potential PHP notices or errors that randomly pop will end commented and not breaking the DOM.

What is the best way to display HTML content using PHP?

I have a php function as shown below, which takes in an array that has values from an SQL query (in another, not shown function). In this case, the SQL query returns a set of filenames and their associated picture names.
// Take in an array of filters;
// each element is a dictionary of column name
// to the value of that row from SQL query
function displayFilters($filters) {
foreach($filters as $filter){
//output images in img tags, with their appropriate classes
echo " <div class='w3-quarter'>
<div class='w3-card-2'>
<img src='images/".$filter['File_Name']."' style='width:100%'>
<div class='w3-container'>
<h4>".$filter['Filter_Name']."</h4>
</div>
</div>
</div>";
}
}
Now, this works fine and will properly display the images as I want. However, I keep having to modify this code, change classes, properties and what not, and if I need to add/modify to the div, I have to go into this function to change everything. Is there a better way to do this than going into the echo function to change it? I'd rather not have to use Javascript if possible, but if that is the only clean way to do it, can someone point me to a way to do this?
<?php function displayFilters($filters) {
foreach($filters as $filter){ ?>
//output images in img tags, with their appropriate classes
<div class='w3-quarter'>
<div class='w3-card-2'>
<img src='images/<?=$filter['File_Name']>' style='width:100%'>
<div class='w3-container'>
<h4><?=$filter['Filter_Name']></h4>
</div>
</div>
</div>
<?php
}
} ?>
I do it this way and it seems easy than learning a new template engine
Use a PHP Template Engine
http://www.smarty.net/
Smarty is fast and lean with a small memory footprint.
http://twig.sensiolabs.org/ (Looks remarkably like Dwoo)
Twig is a modern template engine for PHP (Fast, Secure, Flexible)
http://dwoo.org/ (Inspired by Smarty)
Dwoo is a templating system used to make creating websites easier and more structured.
http://platesphp.com/ (Inspired by Twig)
Plates is a native PHP template system that’s fast, easy to use and easy to extend.
http://phptal.org/
PHPTAL is a PHP implementation of ZPT work. To be short, PHPTAL is a XML/XHTML template library for PHP.
I have written how to retrieve query and how to display in below code.
You can use this one. you can also use image tag within table <tr> tag.
$con=mysqli_connect('localhost','username','password','databasename');
$sql="SELECT `COL 1` , `COL 2` , `COL 3` , `COL 4` , `COL 5` , `COL 12` FROM `TABLE` WHERE 1 ORDER BY `COL 3` ;";
$result=mysqli_query($con,$sql);
<table style="width:100%" >
<tr>
<th>Col1</th>
<th>Clo2</th>
<th>Col3</th>
</tr>
<?
while ($row=mysqli_fetch_row($result))
{
echo "<tr><td>".$row[0]."</td><td>".$row[1]."\t".$row[2]."\t".$row[3]."\t".$row[4]."</td><td>".$row[5]."</td></tr>";
}
?>
</table>

numbers in a alphanumeric string formating

I have the following javascript to format the numbers in a string.
<?php if(count($businessesArray) > 0) { foreach($businessesArray as $business) { ?>
<div id="number2"><?php echo $business["name"]; ?></div></p>
<script type="text/javascript">
$('#number2').html(($('#number2').html()).replace(/[0-9]/gi, '<big>$&</big>')) ;
</script>
<?php } } else { ?>
There is not any business added yet.
<?php } ?>
http://jsfiddle.net/wLd5E/5/
but if apply to a value in a loop it format the first record only.
Where am I wrong?
Regards:
html elements have to have a unique ID. here you use id="number2" for all the DIV elements, this way your javascript always formats the first one.
try using unique ID in the foreach to give the DIV and the JQuery selector.
you can also just use a class on these DIV elements, and then you can format the content with one line of javascript using a JQuery selector for that class, it will do the trick for all elements of that class.

Put JSON data into html form input hidden?

I'm building a rich web application that uses a lot of data. When I'm building it I found that I was repeating myself over and over.
This is the problem. I need to put hidden application logic into HTML elements to represent the data being viewed by the client.
This is a solution I found some time ago:
<a href="bla" data-itemId="1" .... more data.
There are two problems with this method.
I can't represent arrays.
It's just ugly.
I searched for a solution but did not find anything. I also went to facebook, opened firebug,
and found this:
{"actor":"19034719952","target_fbid":"454811929952","target_profile_id":"19034719952","type_id":"7","source":"1","assoc_obj_id":"","source_app_id":"","extra_story_params":[],"content_timestamp":"1324385453","check_hash":"9eabc3553e8a2fb6"}
This json was inside an input[type=hidden] element.
I tried to do the same thing with json_encode();
<input type="hidden" name="track" value="{"_id":{"$id":"4eee908f615c2102e9010000"},"link":"george-wassouf-flag-of-my-heart-longing","file":"\/m\/tracks\/t.4eee908daca2a3.49941874.mp3","lyrics":null,"freezed":false,"hits":0,"images":{"large":"\/assets\/static\/default.track.large.jpg","thumb":"\/assets\/static\/default.track.thumb.jpg","icon":"\/assets\/static\/default.track.icon.jpg"},"duration":"300","created":{"sec":1324257423,"usec":78000},"albums":[{"_id":{"$id":"4eee8d63615c21f6e7000000"},"names":{"ar":"\u0643\u0644\u0627\u0645\u0643 \u064a\u0627 \u062d\u0628\u064a\u0628\u064a","en":"Kalamak ya Habibi"},"link":"george-wassouf-kalamak-ya-habibi","images":{"original":"\/m\/pics\/albums\/o.4eee8d612c3183.11879972.jpg","poster":"\/m\/pics\/albums\/p.4eee8d63967072.02645896.jpg","large":"\/m\/pics\/albums\/l.4eee8d63a89111.20372767.jpg","small":"\/m\/pics\/albums\/s.4eee8d63b18927.47242533.jpg","thumb":"\/m\/pics\/albums\/t.4eee8d63b7f1f4.11879932.jpg","icon":"\/m\/pics\/albums\/i.4eee8d63bf1304.59902753.jpg"}},{"_id":{"$id":"4eee8d63615c21f6e7000000"},"name":"Kalamak ya Habibi","link":"george-wassouf-kalamak-ya-habibi"}],"name":"Flag of my heart longing","title":"Flag of my heart longing","mp3":"\/m\/tracks\/t.4eee908daca2a3.49941874.mp3","poster":"\/m\/pics\/artists\/p.4eee85cd7ed579.65275366.jpg","artists":[{"_id":{"$id":"4eee85cd615c21ece6000000"},"name":"George Wassouf","link":"george-wassouf"}]}" />
But when I try getting the value I get this {.
I have tried all constants like JSON_HEX_TAG and did not find any questions of this type.
How can I put JSON into HTML correctly and then get it with jquery/javascript?
Your string is correct, but it cannot be defined in HTML because it contains double quotes.
HTML requires you to escape double quotes when you are defining a String that is itself enclosed within double quotes. The appropriate way of doing this is using the HTML entity:
value="""
From PHP:
Use htmlspecialchars or htmlentities (http://www.php.net/manual/en/function.htmlspecialchars.php). In any case, you normally should be using this over EVERY value you write to the client browser (not doing so may result in security risks).
From Javascript:
If you need to do this from Javascript, you can programatically set the value of the hidden element (provided your JSON string is already contained in a Javascript variable). This way you don't have to worry about encoding the string literal:
hiddenElement.value = yourString;
In order to get an escape function you can use, maybe check this thread: Escaping HTML strings with jQuery .
Best way for me was to use html & quot;
for example i do this:
<input type="hidden" id="v" value="[{"id":"1"}]" >
instead of
<input type="hidden" id="v" value="[{"id":"1"}]" >
in your input tag, the value attribute in which you are trying to put json array. Look at it. you are putting ". Second " is ending the attribute value. thus it is being interpreted as value = "{". you need to escape those ". Use single quotes ' instead. And check then
It seems my answer is late, but I want to contribute to those who come later.
Before coming here you have the concept of HTML.Use single quotes ' , Should not do that, although it still works, it is against the HTML principle .
The best way is: Use htmlspecialchars or htmlentities. #jjmont said above.
I have a small example:
<input id="jsondata" value="<?php echo htmlspecialchars( json_encode($data), ENT_COMPAT ); ?>" >
||
<input id="jsondata" value="<?php echo htmlspecialchars( json_encode($data), ENT_NOQUOTES ); ?>" >
php
set array in
<input type="checkbox" name="deviceInfo" value="<?php print_r(json_encode(array_filter($array_data), JSON_FORCE_OBJECT));?>" />
?>

Categories