PHP print message when a div is present on specific page - php

I am trying to print a message (link) through PHP if a div is present on a page. Basically the div is present on some product pages on an ecommerce website, while it is not present on other product pages. The ecommerce is a Woocommerce and that's why I am using Woo hooks in the code.
Basically I get nothing in return (even when visiting pages where the div is present). What am I missing?
add_filter('woocommerce_before_add_to_cart_button', 'size_guide_display', 15);
function size_guide_display() {
$sizeguide = $html->find("div#tab-SizeChart_tab");
if ($sizeguide) :
echo 'Storleksguide';
endif;
}
I'll be very happy for any reply :-) Pretty novice with PHP.
Thanks!

Due to the information you've provided I guess using JavaScript on the client-side would be your way to go.
document.addEventListener("DOMContentLoaded", () => {
const sizeChartTabEle = document.querySelector("div#tab-SizeChart_tab")
const storleksGuideLinkEle = document.createElement("a")
storleksGuideLinkEle.title = "Storleksguide"
storleksGuideLinkEle.href = "#tab-SizeChart_tab"
storleksGuideLinkEle.classList.add("size_guide_link")
storleksGuideLinkEle.innerText = "Storleksguide"
sizeChartTabEle?.append(storleksGuideLinkEle)
})
This code creates an event listener DOMContentLoaded (see this StackOverflow answer to learn more about it, speaking very basic - it waits for your contents being loaded) and executes the part in the curly brackets.
Your div#tab-SizeChart_tab is queried and afterwards appended by a newly created a element storleksGuideLinkEle.
If you make sure this code is only executed on pages that you need it, this should do the job.

Related

html - Hidden content in div tag

I would like to download content of certain page and get one number from it (still not sure how, probably using PHP DOM interface). I opened the page, started Firefox's debugging, picked the element with number and found out that is in <div id="lblOptimizePercent" class="wod-dpsval">98.4%</div> (98.4% is what I am looking for). So I opened its source code, Ctrl - F for lblOptimizePercent and all I found is this <div id="lblOptimizePercent" class="wod-dpsval"></div> without any content. What I've done wrong? Or is it some site's protection not to steal contents?
Link to the original site
Normally, to scrape the page from PHP, you would have to
save the page
extract the value you want from HTML via a regular expression
alternatives include using SimpleXML for DOM querying...
The piece of HTML we are look at is:
<div id="lblOptimizePercent" class="wod-dpsval">DATA</div>
<?php
$text = file_get_contents('http://www.askmrrobot.com/wow/optimize/eu/drak%27thul/Ecclesiastic');
$regexp = '^<div id=\"lblOptimizePercent\" class=\"wod-dpsval\">(.*)<\/div>^';
preg_match($regexp, $text, $matches);
$percentage = $matches[1];
echo $percentage;
This should give you DATA - the percentage value. But this doesn't happen! Why:
The data is dynamically inserted by a Javascript on client-side.
The id or class selector is used for DOM querying (element selection), then the data value is added.
http://api.jquery.com/id-selector/ - http://api.jquery.com/class-selector/
jQuery example
On this site they deliver <div id="lblOptimizePercent" class="wod-dpsval"></div>to the client and then they use an update query like this: $("#lblOptimizePercent").text("100%"); to update the percentage value.
If you want to query it on client-side, you might use $("#lblOptimizePercent").text();**
Try this in your console. It returns the percentage value.
How to scrape this page?
If you want to scrape this page with dynamic data, you need something like a Browser Environment for scraping: PhantomJS or SlimerJS are your friend.
Open the page with PhantomJS, launch the jQuery cmd from above and done.
This snippet should get you pretty close. You might save it as scrape.js then execute it with Phantom.
var page = require('webpage').create();
page.open('http://www.askmrrobot.com/wow/optimize/eu/drak%27thul/Ecclesiastic', function() {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.evaluate(function() {
alert(
$("#lblOptimizePercent").text()
);
});
phantom.exit()
});
});
You can also save the "evaluated page" (now with data) and do the extract with PHP.
That's exactly like: Save Page in your browser and working on the saved HTML file.
In Firebug or another webdeveloper tools you see the generated content, in Source code there is a blank element only.
First time, blank element is shown (during rendering site) and than using JS the content is filled.
Googlebot etc. can´t see this JS-generated content, but it´s no problem in this case.
Code:
document.getElementById('lblOptimizePercent').innerHTML = '94%';
Or similarly using jQuery:
$('#lblOptimizePercent').html('94%');
// need to load jQuery before, of course

jQuery .load() interfering with shopping cart function

I've been struggling for 2 hours now, searching all over for a solution to this.
I'm working with a Zen-Cart installation, and I've decided to thrown on some dynamic banners. Basically I use jQuery.get() to load a URL from banner1.php - banner1.php has an array of a few urls (which are product pages), and it echoes out a random url from the array.
Once the random URL is loaded by jQuery, I then use the jQuery.load() function to load the image of the product, the price of the product and the name of the product.
All this works absolutely fine, but the problem is that it seems the load() function is interfering with my Zen-Cart "redirect" function. Say if you are viewing a product, let's call it "Product A" - and you decide to log in from that page by clicking the "Login" button - what happens is that you are taken to the Login page, you enter your login details, and hit "Submit". The standard outcome is that if you are logged in successfully, you are taken back to the "Product A" page. But with my little dynamic jQuery banner concoction, instead of redirecting back the "Product A", it loads one of the pages that the jQuery.load() used to generate the random banner. I have 3 banners, each dynamically loading a random url, but here is an example of Banner 1:
<script type="text/javascript">
$.get("banner1.php", function(getbannerlink1) {
$( document ).ready(function() {
$("#banner1").load(getbannerlink1+ " #globalproductimage");
$('#banner1name').load(getbannerlink1+ " #productName", function(result) {
var banner1text = $('#banner1name').html();
banner1text = jQuery(banner1text).text();
$("#banner1name").html(banner1text);
});
$('#banner1price').load(getbannerlink1+ " #productPrices", function(result) {
var banner1prices = $('#banner1price').html();
banner1prices = jQuery(banner1prices ).text();
$("#banner1price").html(banner1prices );
});
var bannerlink1 = $("<a>").attr("href", getbannerlink1);
$("#banner1name").wrap(bannerlink1);
$("#banner1price").wrap(bannerlink1);
$("#banner1").wrap(bannerlink1);
});
});
</script>
The thing is I'm not too concerned about the wrongful redirection once a customer logs in, the problem also occurs most disappointingly when the customer once to actually Checkout. For instance, if they were to have products in their shopping basket, click the Checkout button, which then asks them to login, and once they login, instead of continuing with the standard shopping cart function of taking them to the first step of the checkout process, it redirects them to one of the pages that the dynamic banner has loaded. I don't know how to sort this out, I tried some weird things to no avail. For the sake of reference, this might be needed, this is the Zen-Cart function that handles redirection after a login:
if (sizeof($_SESSION['navigation']->snapshot) > 0) {
// $back = sizeof($_SESSION['navigation']->path)-2;
//if (isset($_SESSION['navigation']->path[$back]['page'])) {
// if (sizeof($_SESSION['navigation']->path)-2 > 0) {
$origin_href = zen_href_link($_SESSION['navigation']->snapshot['page'], zen_array_to_string($_SESSION['navigation']->snapshot['get'], array(zen_session_name())), $_SESSION['navigation']->snapshot['mode']);
// $origin_href = zen_back_link_only(true);
$_SESSION['navigation']->clear_snapshot();
zen_redirect($origin_href);
} else {
zen_redirect(zen_href_link(FILENAME_DEFAULT, '', $request_type));
}
Please help! Perhaps there is an easier way I should be doing this :/
I noticed that the page it loads is always the last banner that jQuery.load() loaded. Like I mentioned there are 3 banners in total, so if Banner 2's price was the last one to load, that's the URL that's loaded in the redirection.
Edit:
banner1.php (this simply generates a random url from an array, but currently for testing purposes I only have one URL in the array):
<?php
$strings = array('http://example.com/index.php?main_page=product_info&cPath=3&products_id=104');
echo $strings[array_rand($strings)];
?>
It appears that the banner page is setting the snapshot href. I assume you are including some of the Zen cart libraries in your banner urls that are setting the Session navigation snapshot. You maybe able to set something to ignore your url for the snapshot.
Adding the banner code may help solve this issue.
Although I would not recommend it, you could add logic to not redirect to certain pages after login.

change value of a php variable on ajax content load

I thought this would be really simple but obviously after a couple of days trial and no success I have to ask the people to help, looked everywhere.
right im basically creating a php template without much guidance on the foundation 4 framework with is a responsive framework. Now this framework is rather basic and so to add page transitions ive had to use jquery to do what i believe is an ajax call to take "content" from another page and display it on the template page index.html
for which I am currently using the following
<script>
$(document).ready(function() {
$('nav.top-bar > section.top-bar-section > ul.right > li > a').click(function() {
var toLoad = $(this).attr('href')+' #content';
$('#content').hide(1000,loadContent);
$('#load').remove();
$('#main_wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('fast');
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-0);
function loadContent() {
$('#content').load(toLoad,showNewContent);
}
function showNewContent() {
$('#content').show(1000,hideLoader);
}
function hideLoader() {
$('#load').fadeOut('fast');
}
return false;
});
});
</script>
NOW before i changed over to using ajax and jquery i was operating the menu "active" class and the page name with a simple variable set on each page in the first line listed as $page='' and then the page name
now that im loading the content with ajax even if i include this variable in the content of the new page it will not update in either the or the menu title
im very sorry i dont write things correctly im new to this forum thing
thank you for the help in advance
:) I prefer someone to explain what i need to do and how to do it rather than just copy and pasting code as im a learner :)
You probably want to load the page and parse the result in jQuery to get the new page’s <title> tag and set the requesting page’s <title> tag.
The only thing I’d ask is: why are you doing this? Are you just wanting AJAX page navigation in your website instead of the traditional propagating navigation?
I am only able to answer one part of your question due to extreme confusion, so:
First off, here's why your url changes:
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-0);
You are modifying it with that line. That line, however, has an interesting little quirk:
attr('href').length-0
at the end. Why the -0? That would make no difference. I'd clean it up.
Outside of that, I'm incredibly confused with what you're asking so let me try rephrasing it and you can tell me what I'm missing.
You want to have a user click on a navigation link, and load that link's content via an AJAX call using jQuery, and then replace the content on the page with the newly loaded page, correct?
When you say "right on top main page i have variable $page = then the page name", what do you mean by "main page"? Do you mean it's a line of text in HTML? Part of a script that you haven't included here? Part of your PHP code?
And then you say "ive tried including the tag in a div that changes along with the above content"- what is "the tag"?
By reading this 4 or 5 times I could barely discern the above understanding of what you're trying to do.
Please make heavy edits to you question- it's incredibly hard to understand.
Lastly, why are you trying to replace the browser's functionality of a user clicking a link and loading content? That's what the browser is for. The browser also, conveniently, has a loading indicator in the url bar usually (or some form thereof), letting the user know the content is still loading.
function loadContent() {
$('#content').load(toLoad,showNewContent);
}
So first off, look at the jQuery doc for the load method:
http://api.jquery.com/load/
Your issue is that it is calling for three arguments, and you are passing two. If there are multiple arguments listed and you only want to pass SOME of them, you still need to supply a null value for the ones you want to "skip". Try changing your call to this:
function loadContent() {
$('#content').load(toLoad, null, showNewContent);
}
You'll notice that I'm passing "null". If that doesn't work, pass an empty string, like this:
function loadContent() {
$('#content').load(toLoad, "", showNewContent);
}
That second argument is data to be passed with the request. It's the THIRD argument that you list as your callback, which as far as I can tell is where you're making the mistake.

Use Jquery to prevent page reloading pressing anchor

I am trying to use the jquery to Prevent page realoading. I have the whole code php done... and is functional. if you can please go to http://www.jonathansconstruction.com/gallery3.php and click on the different gallery SUbmenus for category View All, Kitchen etc... i'm using get for variables. However, I would like to use a jquery to process the php so i dont have to include it into the gallery.php and also, to prevent page reloading because it brings the page back up and that could be confusing. Any hlep willl be greatly appreciated THanks
UPDATE, Thanks for everyone that helped:
SO far i made an advance on the website, Corrected URL was edited on top of the post
Everything is working smoothly on the effects of quicksand.. HOwever, Lytebox Doesn't Load when a quicksand effect is placed. , at the beginning it loads just fine, but right after pressing one of the menus for the quicksand effect. It stops working. Also, I want to style my menu buttons as is in http://www.jonathansconstruction.com/gallery.php. I see jquery doesnt add and witht the sample I downloaded. and also the that says "gallery Pictures" dissapears ont he quicksand demo.
Any Help is appreciated. Below is the script.js code I have modified so far
$(document).ready(function(){
var items = $('.photo_show figure'),
itemsByTags = {};
// Looping though all the li items:
items.each(function(i){
var elem = $(this),
tags = elem.data('tags').split(',');
// Adding a data-id attribute. Required by the Quicksand plugin:
elem.attr('data-id',i);
$.each(tags,function(key,value){
// Removing extra whitespace:
value = $.trim(value);
if(!(value in itemsByTags)){
// Create an empty array to hold this item:
itemsByTags[value] = [];
}
// Each item is added to one array per tag:
itemsByTags[value].push(elem);
});
});
// Creating the "Everything" option in the menu:
createList('View All',items);
// Looping though the arrays in itemsByTags:
$.each(itemsByTags,function(k,v){
createList(k,v);
});
$('#gallery_menu nav a').live('click',function(e){
var link = $(this);
link.addClass('current').siblings().removeClass('current');
// Using the Quicksand plugin to animate the li items.
// It uses data('list') defined by our createList function:
$('.photo_show').quicksand(link.data('list').find('figure'), {adjustHeight: 'dynamic'} );
e.preventDefault();
});
$('#gallery_menu nav a:first').click();
function createList(text,items){
// This is a helper function that takes the
// text of a menu button and array of li items
// Creating an empty unordered list:
var ul = $('<ul>',{'class':'hidden'});
$.each(items,function(){
// Creating a copy of each li item
// and adding it to the list:
$(this).clone().appendTo(ul);
});
ul.appendTo('.photo_show');
// Creating a menu item. The unordered list is added
// as a data parameter (available via .data('list'):
var a = $('<a>',{
html: text,
href:'#',
data: {list:ul}
}).appendTo('#gallery_menu nav');
}
});
ANOTHER EDIT :
All Looking good So far Fixed Lot of problems, However, for some reason, the span I had on teh static html dissapears from display and even html code when loading jquery quicksand code..?? Here is the code i have on the html part of the website that Does Not appear on the live website for some reason.
<div id="portfolio">
<div class="photo_show"><span>Gallery Pictures</span>
the span part doesnt appear, dont know why
I had the TOp Part Resolvd. just moved the on top of photo_show div and edited positioning... HOPEFULLY Last Edit
the jquery for quicksand made my calendar dissapear, checked and yes it was some jquery conflict but dont know what can be causing it.. also the form validation not working as well ... any help is appreciated!
I visited your webpage link after correcting a typo in the URL for word construction.
I also see the problem that the page reloads when clicking on a sorting filter such as View All, Kitchen, and Miscellaneous which is what you want to prevent.
Unfortunately, those buttons are using URL Links asking to reload the webpage with a filtered option via query string. Nothing can be done for that method of filtering, your just going to reload the webpage since filtering is done on page load.
Perhaps this DEMO shows what you want to accomplish since it does not reload the webpage. That demo has markup that is easy to create and maintain which is build using the Quicksand jQuery Plugin. The tutorial for that demo is accessed using the link at the bottom right, but looking at the source HTML file shows how simple it is.
I made a downloadable demo using both Quicksand and Shadowbox, a lightbox alternative HERE, which might interest you since your webpage is linking the filtered icon results to a lightbox alternative named Lytebox.
Since your edit reflects your interest in Lytebox, the following markup will reinitialize that lightbox alternative after a filtering event has occurred with Quicksand. Update your script.js file accordingly.
$('.photo_show').quicksand(link.data('list').find('figure'), function(){
adjustHeight = 'dynamic';
initLytebox();
});
I also made a correction to your existing adjustHeight since it was using a semicolon instead of an equal sign, but the correct location and use of that is for something unrelated.
The reason that you are not seeing the bullets is because your not using ul/li tags that the demo is using.

Keep a div from reloading

Basically, I want the same effect as the oldschool html 'frameset' I think.
Take a look at this page please:
http://onomadesign.com/wordpress/identity-design/alteon-a-boeing-company/
If a user selects a project from industry -> transportation for example, I would like that the right scrollmenu keeps its initial state when the new project page comes up. So they won't get lost and have to click again to be in the same submenu section.
So, the right thumbnail navigation should stay in the same way, I don't want it to reload.
Do I have to do it with frames or iframes? Or can I make some kind of jQuery call to 'not reload' that div? Maybe PHP? I'm sorry, I am not a programmer from origin.
Update:
Guys, I managed to put the whole thumbnail navigation code into a seperate php file, called sidebar.php. Now this gets called in my single.php (Wordpress) by <?php get_sidebar(); ?>.
Should it now be easier to make this sidebar.php NOT refresh on page reload? I've been looking at cookies, php sessions, iframes.. but I can't get it to work.
Any more help would be greatly appreciated!
Facebook kinda does this without frames for optimization's sake. They take every single link and, if supported, using AJAX to load the page content without reloading the layout.
Obviously, this sort of thing may require significant restructuring of the internals of your app. Another option is to simply store the menu's state as a cookie on link click (see the jQuery Cookie plugin) and, on every reload, either have Javascript look at the cookie and dynamically restore the menu to its correct state, or use your internal PHP to read the cookie and decide what menu to display.
But if you get really desperate, you may end up falling back on frames. Sometimes that can be okay - but try everything else first :)
You also can detect what menu item was activated (you got the page request due to clicking on the corresponding link) and use this information to restore/select this menu item.
At least that is what I do and... No cookies or AJAX required!
You can use a technique known as "AHAH" Asynchronous HTML and HTTP. Essentially you're doing a jQuery
$.post("whatever.html",function(data) {
$("contentdivelement").html(data);
}
You can wrap this in a function like:
updateContent(sPage) {
$.post(sPage,function(data) {
$("contentdivelement").html(data);
}
}
This will load the content from your "frame" page into the div without reloading the page.
You can also bind to each of the navigation links and use their HREF as your path to load in your content div such as:
$(".menuLink").click(function() {
var menuLink = $(this).attr('href');
updateContent(menuLink);
/* prevents the browser from taking the parent to that link */
return false;
});
ADDITION:
Your menu may look like this:
<ul class="myMenu">
<li>Frame 1</li>
<li>Frame 2</li>
</ul>
Also,
If you want it to remember the page you're on you can use cookies or #anchors. There are many ways to add "tab" or "menu" anchors but one way would just be to use a jQuery plugin.
The most COMMON and TRENDY way to do it is to use #anchors. Your browser address bar ass #frame1 to the end so when the page is refreshed or reloaded it will load up "frame1" automatically with some additional code.
You can even called the anchor #/frame1.html and read the anchor in
$(document).ready(function() {
/* you'll need to either use a plugin or parse out the anchor from your current browser address bar */
updateContent(anchorContentVar);
});
Instead of updating your content using click-handlers I suggest a slightly different approach. Just replace your hyperlinks with this kind of link:
#info_page
Now set up a simple interval that reads out the current URL and updates the DIV accordingly:
__LOC = document.location.href;
setInterval(function(){
if (__LOC!=document.location.href) __LOC=document.location.href;
var fetchURL = __LOC.split("#")[1];
$.get( "/getcontent/"+fetchURL, function(d){ $("#mydiv").html( d ); } )
} 1000);
This allows visitors to use bookmarks as well.

Categories