Appending PHP generated HTML to document fragment - php

I need to append a large amount of PHP generated HTML (5000 div elements) to a document fragment and append that to the body of the page.
Example HTML (this is just part of the StackOverflow source, but it is similar):
<div itemscope itemtype="http://schema.org/Article">
<link itemprop="image" href="http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png">
<div id="question-header">
<h1 itemprop="name">Access PHP variable in JavaScript [duplicate]</h1>
</div>
<div id="mainbar">
<div class="question" data-questionid="4287357" id="question">
<div class="everyonelovesstackoverflow" id="adzerk1">
</div>
<table>
<tr>
<td class="votecell">
<div class="vote">
<input type="hidden" value="4287357">
<a class="vote-up-off" title="This question shows research effort; it is useful and clear (click again to undo)">up vote</a>
<span class="vote-count-post ">2</span>
<a class="vote-down-off" title="This question does not show any research effort; it is unclear or not useful (click again to undo)">down vote</a>
<a class="star-off" href="#" title="This is a favorite question (click again to undo)">favorite</a>
<div class="favoritecount"><b>1</b></div>
</div>
I have broken the problem into 2 smaller problems:
Store PHP variable in Javascript: var tmp = "<?php Print($DOM); ?>";
Append HTML into document fragment (Looked at this but it's about something else)
How can I get this to work?

I have been using jsrender a lot lately to deal with formatting large amounts of JSON/Javascript data into HTML. This lets me pack more data into fewer bytes, and then have the client create large swaths of HTML using a template. Here is a simple example:
<html><head>
<script type="text/x-jsrender" id="historyTemplate">
{{if orders}}
<h1>Your Order History</h1>
<table>
<thead>
<tr><th>Order Name</th><th>Amount</th><th>Status</th><th>Tracking</th></tr>
</thead>
<tbody>
{{for orders}}<tr>
<td>{{>orderName}}</td>
<td>{{>total}}</td>
<td>{{>status}}</td>
<td>{{if trackingNumber}}
<a target="_new" href="{{:trackingURL}}">{{>trackingNumber}}</a>
{{/if}}</td>
</tr>{{/for}}
</tbody>
</table>
{{else}}
<h1>You have no prior webstore orders.</h1>
{{/if}}
</script>
<script type="text/javascript">
var customer = {
name: 'Joe Bloe',
orders: [
{ orderName: 'Joe Bloe 2013/04/01 #595',
total: 59,
status: 'Not yet shipped',
trackingNumber: null,
trackingUrl: null
},
{ orderName: 'Joe Bloe 2013/04/15 #876',
total: 32.50,
status: 'Shipped',
trackingNumber: '55512345',
trackingUrl: 'http://www.shipper.com/track?55512345'
},
]
};
$("#orderDiv").html( $('#historyTemplate').render(customer) );
</script>
</head><body>
<h1>Your Order History</h1>
<div id="orderDiv"> </div>
</body></html>
The data can be part of the page when it is served, or it can arrive via AJAX or JSONP, or it can be dynamically generated by the client itself. So far, I have never had a performance problem with it.

Related

Lightbox unable to Enlarge Images

This week our product pages have been not working as intended. When clicking the product image thumbnail to enlarge, the lightbox window loads and just continues to load, never displaying the image. It was working before and I have no access to these scripts and files, since they are loaded through PHP that I have no access to. We are on BigCommerce's platform, but BC will not help me because we have customized our template. I have poured through the source code and cannot find what could be causing this issue. Any help is greatly appreciated.
Link to a product page: http://www.inflatableboats.net/demo-zodiac-pro-open-650-t-top-neo-2016-with-twin-yamaha-f70-four-stroke/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://opengraphprotocol.org/schema/">
%%Panel.HTMLHead%%
<body>
<script type="text/javascript" src="%%GLOBAL_AppPath%%/javascript/jquery/plugins/validate/jquery.validate.js?%%GLOBAL_JSCacheToken%%"></script>
<script type="text/javascript" src="%%GLOBAL_AppPath%%/javascript/product.functions.js?%%GLOBAL_JSCacheToken%%"></script>
<script type="text/javascript" src="%%GLOBAL_AppPath%%/javascript/product.js?%%GLOBAL_JSCacheToken%%"></script>
<div id="Container">
%%Panel.Header%%
<div id="Wrapper">
%%Panel.WrapperBanner%%
<div class="Left" id="LayoutColumn1">
%%Panel.SideCategoryList%%
%%Panel.SideNewProducts%%
%%Panel.SideNewsletterBox%%
%%Panel.SideLiveChatServices%%
</div>
<div class="Content" id="LayoutColumn2">
%%Panel.ProductBreadcrumb%%
%%Panel.ProductDetails%%
<div id="Fees">
<p id="FeeHeader"><strong>Standard Fees Apply</strong></p>
<a class="tooltip" style="float: left;" href="#"> PDI: <span> <img class="callout" src="http://inflatableboats.net/template/feebox/callout.gif" alt="" /> <strong>Pre-Delivery Inspection</strong><br /> Standard Fee for services performed and products used on each new vessel, requested by all manufacturers to validate and assist in all warranties.<br /><br />We install a deep cycle marine battery, fully rig steering components, complete electrical and systems check. We conduct a full system check on the motor, fill with oil, fluids, and fuel, then test run in a test tank.<br /><br />Once everything is tuned and prepared, a sea trial is performed with two Specialists to achieve ideal RPM-to-top-speed ratio, ensuring the boat gets on plane properly, and all systems operate on water.<br /><br />Afterwards a full detail is performed on the tubes, deck, and hull to be turn-key ready for the customer. </span> </a>
<p style="float: left;"> </p>
<a class="tooltip" style="float: left;" href="#"> Destination Fee: <span> <img class="callout" src="http://inflatableboats.net/template/feebox/callout.gif" alt="" /> <strong>Destination Fees are set by Zodiac.</strong><br /> Standard Fee both vehicle and vessel dealerships are charged from a manufacturer to ship product to dealerships </span> </a>
<p style="float: left;"> </p>
</div>
<div id="quote">
<a class="btn lightbox-40737220632144" style="cursor: pointer;"><img id="quotebutton" style="" src="http://inflatableboats.net/template/img/request-a-quote.png" name="quotebutton" /></a>
<img id="financebutton" style="" src="http://inflatableboats.net/template/img/finance-button.png" name="quotebutton" />
</div>
%%Panel.ProductTabs%%
%%Panel.ProductDescription%%
%%Panel.ProductVideos%%
%%Panel.ProductWarranty%%
%%Panel.ProductOtherDetails%%
%%Panel.SimilarProductsByTag%%
%%Panel.ProductByCategory%%
%%Panel.ProductVendorsOtherProducts%%
%%Panel.SimilarProductsByCustomerViews%%
</div>
<div class="Right" id="LayoutColumn3">
%%Panel.SideCurrencySelector%%
%%Panel.SideProductAddToWishList%%
%%Panel.SideProductRelated%%
%%Panel.SideProductRecentlyViewed%%
</div>
<br class="Clear" />
</div>
%%Panel.Footer%%
</div>
<script>
$(document).ready(function(){
$("#ProductOtherDetails .ProductDetailsGrid .DetailRow").each(function(){
var label = $(".Label",this).text();
if ( label === 'PDI:') {
var pdiAmount = $(".Value",this).text();
pdiAmount = pdiAmount.replace(/\t/g,"");
pdiAmount = pdiAmount.replace(/\n/g,"");
//console.log("PDI is " + pdiAmount);
$("#Fees p:nth-of-type(2)").text(pdiAmount);
}
if ( label === 'DF:') {
var dfiAmount = $(".Value",this).text();
dfiAmount = dfiAmount.replace(/\t/g,"");
dfiAmount = dfiAmount.replace(/\n/g,"");
//console.log("DF is " + dfiAmount);
$("#Fees p:nth-of-type(3)").text(dfiAmount);
}
})
});
</script>
<script src="https://form.jotform.com/static/feedback2.js?3.3.REV" type="text/javascript"> var JFL_40737220632144 = new JotformFeedback({ formId: '40737220632144', base: 'https://form.jotform.com/', windowTitle: 'Request a Quote', background: '#B10D13', fontColor: '#FFFFFF', type: 'false', height: 500, width: 700, openOnLoad: false }); </script>
</body>
</html>
I think that maybe it is caused by a TypeError, but do not know how I can fix this. Image linked below. It points me to the first line of the source, which is the HTML Doctype. That doesn't make sense to me.

How can I remove the <p style="text-align:center"> (or left, right. The paragraph comes from database) using PHP?

I have this html code that came from my database (I used TinyMCE to save the data)
<p style="text-align: center;">Come on grab your friends</p>
<p style="text-align: center;">Go to very distant lands</p>
<p style="text-align: center;">Jake the Dog and Finn the Human</p>
<p style="text-align: center;">The fun never ends</p>
<p style="text-align: center;"><strong>Adventure Time!</strong></p>
How can I remove those <p></p> tags considering that there can be other styles applied when using TinyMCE?
To remove HTML tags from a string you can use strip_tags():
$str = '<p style="text-align: center;">Come and grab your friends</p>';
$str2 = strip_tags($str);
echo $str2; // "Come and grab your friends"
To keep certain tags, you can add an additional parameter:
$str = '<p style="text-align: center;"><strong>Adventure Time!</strong></p>';
$str2 = strip_tags($str, "<strong>"); // Preserve <strong> tags
echo $str2; // "<strong>Adventure Time!</strong>"
The second parameter is a string listing each tag you don't want stripped, for example:
$str2 = strip_tags($str, "<p><h1><h2>"); // Preserve <p>, <h1>, and <h2> tags
For more information, review the PHP documentation linked above.
Although you mentioned that you don't use js, I would strongly encourage you to start using it. You will find it extremely useful in plenty of cases to just interfere to client-side rather than use just server-side procedures (as php does). So, just for the record, here is my suggested jQuery solution:
<html>
<head>
<!-- your head content here -->
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<p style="text-align: center;">Come on grab your friends</p>
<p style="text-align: center;">Go to very distant lands</p>
<p style="text-align: center;">Jake the Dog and Finn the Human</p>
<p style="text-align: center;">The fun never ends</p>
<p style="text-align: center;"><strong>Adventure Time!</strong></p>
<div id="result"></div> <!-- here I have added an extra empty div to display the result -->
<script>
$(document).ready(function() {
$("p").each(function() {
var value = $(this).text();
$("#result").append(value+ "<br>");
$(this).css("display", "none");
});
});
</script>
</body>
</html>
Live example here: http://jsfiddle.net/Rykz9/1/
Hope you (and others) find it useful... Happy coding!

How create a popup on mouseover depending on the item?

I want to create a popup depending on the item. The text to appear is taken from the database depending on each item.Specifically, I have this code:
{foreach $images as $item}
<div class="icoana" id="container">
<img class="icoane" src="{base_url()}assets/image/{$item->code}/{$item->name}">
<div class="detalii">
<table style="font-size: 25px">
<tr><td>Nume:</td><td>{$item->title}</td> </tr>
<tr><td>Lungime:</td><td>{$item->width}&nbsp cm</td> </tr>
<tr><td>Latime:</td><td>{$item->height}&nbsp cm</td></tr>
</table>
</div>
<div class="despre" id="popup"><img src="{base_url()}assets/image/go.jpg" style="weight: 20px; height:20px;" >Mai multe...</div>
</div>
{/foreach}
and when mouseover div class="despre" I want appear a pop-up with text's description stored in {$item->description}. The pop-up I want to look like this: http://creativeindividual.co.uk/2011/02/create-a-pop-up-div-in-jquery/.I would like a link to an example or source code.
Broadly, what you need to do is two steps
1) Print out the div description in the php code immediately below the div mentioned.
So your code becomes.
{foreach $images as $item}
<div class="icoana" id="container">
<img class="icoane" src="{base_url()}assets/image/{$item->code}/{$item->name}">
<div class="detalii">
<table style="font-size: 25px">
<tr><td>Nume:</td><td>{$item->title}</td> </tr>
<tr><td>Lungime:</td><td>{$item->width}&nbsp cm</td> </tr>
<tr><td>Latime:</td><td>{$item->height}&nbsp cm</td></tr>
</table>
</div>
<div class="despre" id="popup"><img src="{base_url()}assets/image/go.jpg" style="weight: 20px; height:20px;" >Mai multe...</div>
<div class="desc" style="display:hidden">
{$item->description}
</div>
</div>
{/foreach}
2) After that use the same code in the link you provided above and modify the the display part
$(function() {
$('.despre').hover(function(e) {
//Code to show the popup
// Modify to use any standard popup library
// The code below , for now display the desc only.
$(this).next().show();
}, function() {
$(this).next().hide();
});
});
For now this will show and hide the div. You can use any ToolTip library to actually display the popup
Examples here : http://www.1stwebdesigner.com/css/stylish-jquery-tooltip-plugins-webdesign/
Regards
Shreyas N

Integrating JQuery into a CMS controlled environment HTML/CSS/PHP on XAMPP server

I'm having a hard time adding dynamic functionality to my website with JQuery.
<table id="structure">
<tr>
<td id="navigation">
<?php echo public_navigation($sel_subject, $sel_page); ?>
</td>
<td id="page">
<?php if ($sel_page) { ?>
<h2><?php echo htmlentities($sel_page['menu_name']); ?> </h2>
<div class="page-content">
<?php echo strip_tags(nl2br($sel_page['content']), "<b><br><p><a>"); ?>
</div>
<?php } else { ?>
<h2>Welcome to my "to the point" news and blog mix.</h2>
<?php } ?>
<br />
<?php
// garbledeegoo starts here
?>
<p>JScript Practice</p>
<div id="jscriptprac">text</div>
<br />
<h2>To Do</h2>
<form name="checkListForm">
<input type="text" name="checkListItem"/>
</form>
<div id="button">Add!</div>
<br/>
<div class="list"></div>
<?php
// garbledeegoo ends here
?>
</td>
</tr>
</table>
the problem is i cant make jquery tag selectors style my navigation where i have SQL statements that retrieve my content.
$(document).ready(function(){
$("*").hover(function(){
$(this).stop(true, true).animate({ width:"+=25px", padding:"+=25px" });
}, function() {
$(this).stop(true, true).animate({ width:"-=25px", width:"-=25px" });
});
});
this is just selecting eveything but it still doesnt select the nav.
<td id="navigation">
<?php echo public_navigation($sel_subject, $sel_page); ?>
</td>
I'd like to add .animate jquery to the subjects and pages which are displayed like a list as a side navbar. is there a way to style a query result?
I apologize for my lack of accurate vocabulary. codeybuzz.com is the website if you are having trouble visualizing what I mean, Instead of changing the color of my nav links on a .hover event, i want to animate them on mouseover with jquery. I think doing it with tables might have something to do with it not being selectable, but I dont know how to change them all to divs and not wreck my css styling that i already have in place.
this is the HTML rendered
<td id="navigation">
<ul class="subjects">
<li>About Codey Buzz</li>
<li>No Rubbish, Blog</li>
<li>Top News</li>
</ul>
</td>
I achieved some kind of effect with this, but it isn't very effective.
$(document).ready(function(){
$("ul.subjects > li").hover(function(){
$(this).mouseenter(function() {
$(this).animate({ width: "+=50px" }).stop(true, true);
});
$(this).mouseleave(function() {
$(this).animate({ width: "-=50px" }).stop(true, true);
});
});
});

most acceptable way to put dynamic html on a page

I would like to append some html to a div when a button is clicked. The only thing that needs to be dynamic about it is that it needs to have a different id the the otherwise identical html above it. So if I have a structure like this:
<div id="container">
<div id="div1" class="inner">
<p id="P1">Some content</p>
</div>
<div id="div2" class="inner">
<p id="P2">Some content</p>
</div>
</div>
and to the end of container i would like to append
<div id="div3" class="inner">
<p id="P3">Some content</p>
</div>
What would be a good method to store this HTML? Keep it all in a php page and post the number the new div's id should be incremented to? Or is is smarter to put the html inside a string, and have a regular expression increment all of the numbers. Or is there some incredibly obvious way to do this that I've completely missed.
Jquery is an option, as that's already on the page.
Also, if this question seems too open-ended, please let me know in the comments how I can change it before closing it.
Thank you very much.
Based on your answers to comments so far (i.e. that the id's aren't really important, and that you will have input elements in the content), I would say that you would want to redo your html to look like this:
<div id="container">
<div class="inner">
<p><input type="text" name="order_item[]" value="" /></p>
</div>
<div class="inner">
<p><input type="text" name="order_item[]" value="" /></p>
</div>
</div>
Note there are no longer id's and I have used array notation for your input elements such that they will be posted as an array to the receiving script (eliminating the need to increment counters in javascript or parse different posted variable names into a usable array in PHP on the server).
And then use something like this in jQuery
$('#button_id').click(function() {
$('#container > div.inner:last').clone().val('').appendTo('#container');
});
Put the HTML you want to add each time into a hidden div, then use jQuery to copy and add that to the relevant location. For instance:
<div id="appendContents" style="display:none;">
<div class="inner">
<p id="P3">Some content</p>
</div>
</div>
then jquery:
var shownDivs = <?php echo $numberOnScreenFromBeginning;?>;
$('#theButtonYouWantClickable').click(function()
{
var newContent = $('#appendContents').clone();
newContent.$('div.inner').get(0).id = 'div'+shownDivs;
newContent.$('div.inner p').get(0).id = 'P'+shownDivs;
// Where does P content come from??
shownDivs++;
$('#container').append(newContent);
});
Try this Please: Working Demo http://jsfiddle.net/eNXmr/
In the code below it will calculate the lenght of the div hence dynamically set the id as 1, 2, 3, and beyond.
Hope it fits you need :)
API used: http://api.jquery.com/append/
Code
$('#hulk').click(function() {
alert("Total div inside ==> " + $('#container').find('.inner').length);
var next_num = parseInt($('#container').find('.inner').length) + 1;
$('#container').append(' <div id="div' + next_num + '" class="inner"><p id="P' + next_num + '">Some content</p></div>');
});​
​
HTML
<div id="container">
<div id="div1" class="inner">
<p id="P1">Some content</p>
</div>
<div id="div2" class="inner">
<p id="P2">Some content</p>
</div>
</div>
<input type="button" value="Click hulk" id="hulk" />​

Categories