Functions value is not defined in PHP and HTML - php

I create this div in PHP and I want to call a function when I double=click on it. However, it tells me that my value isn't defined. Can someone please tell me why?
(Here's the important part of my code in php:
"..//Some mor HTML...value='".$DatabaseID.";' ondblclick='delete_selected(value, 'all', 'child'); ..//Some more HTML.."
I can call a function that doesn't have a value. What am I doing wrong?
Here's the rest if you're interested:
$Object = "<div id='".$DatabaseID."' onclick='sendid(id); highlight(id);' title='".$title."' data-parent='".$ParentID."'data-itemCategory='".$ItemCategory."' value='".$DatabaseID.";' ondblclick='delete_selected(value);' onmouseup='position(id);' style='border:".$border_size."px solid ".$border_color."; top:".$pos_y."px; left:".$pos_x."px; position:".$positionType."; background:".$color.";' class='".$class."'>
<!-- <img src='$img' class='img_status_rwp' style='width:".$img_size."px; height:".$img_size."px; margin-left:-".$img_size."px; margin-top:-".$img_size."px; '></img> --> <div class='item_header'><div class='header_text_cont'><div class='header_span'>".$ItemName."</div><div style='clear:both';></div></div></div>";
Update
I changed the quotation and removed te img-part (since it isn't active):
$Object = '<div id="'.$DatabaseID.'" onclick="sendid('.$DatabaseID.'); highlight('.$DatabaseID.')"; title="'.$title.'" data-parent="'.$ParentID.'" data-itemCategory="'.$ItemCategory.'" value="'.$DatabaseID.'" onclick="show_children(value, "all", "child");" style="border:'.$border_size.'px solid '.$border_color.'; top:'.$pos_y.'px; left:'.$pos_x.'px; position:'.$positionType.'; background:'.$color.';" class="'.$class.'">
<div class="item_header"><div class="header_text_cont"><div class="header_span">'.$ItemName.'</div><div style="clear:both";></div></div></div>';
I belive that the quotationmarks around all and child might be the ones creating some trouble but I don't know what to use instead.
show_children is defined in a JavaScript file that is included to the index.php and I can call other functions in it from index. I don't get any errors when double clicking, however the function is not called. When I successfully call the function using a button I have the following HTML:
<div class="sidebar_button" id="childAll" value="" onclick="show_children(value, 'all', 'child'); " style="font-size:10px">Show All Child Nodes (To RWP)</div>

I think your problem lies here onclick='sendid(id); highlight(id);' your passing id which isn't defigned anywhere. You need to change the code to onclick='sendid(".$DatabaseID."); highlight(".$DatabaseID.");' and then it should work.

Related

PHP check if file_exists without extension then Ajax a div with appropriate media tag (img or video) based on filepath

First posting here. I know inline php is not preferred but I haven't converted all my scripts to echo json_encoded arrays to work in javascript on the client side...so for now, I have inline php.
I do not know the extension of the user uploaded media because it could be a jpg,mp4,etc and upon upload it goes into a media folder with the user id as an identifier.
When my user first loads the div (and html page), the php script cycles through an array and does a fetch_assoc from sql query to the database each time; It returns the (media_id #) and prints out an li with the respective media displayed next to some other values from the query.
I only know the (media_id) and the file path name without the extension. When the page first loads, everything works great and the file_exists function returns correctly.
THE PROBLEM
When I AJAX the div and do the query again, because the user added a row to the database, the new list prints out with all info, BUT the file_exists function doesn't recognize the exact same paths as before and I don't have an img or video on the page.
I copy/pasted the exact same code from the original div and put it in a file for ajax to re-query and print the new li's.
All variables are the same and when I hard code a test filepath, it prints fine. Maybe there's a caching issue?
THE CODE
<?php
$result=$conn->query($select);
$row=$result->fetch_assoc();
?>
<li>
<?php
if ($row['count']>0) {
echo "<div class='media-container'>";
$pathname = "uploads/".$row["id"]."media1";
$testjpg=$pathname.".jpg";
$testjpeg=$pathname.".jpeg";
$testpng=$pathname.".png";
$testmp4=$pathname.".mp4";
if (file_exists($testjpg)==TRUE || file_exists($testpng)==TRUE || file_exists($testjpeg)==TRUE) {
echo '<img src="'.$pathname.'">';
}if(file_exists($testmp4)==TRUE) {
echo "<video></video>";
}
echo "</div>";
}?>
</li>
I could use some advice on how to fix this and how to print appropriate media tags on unknown media types.
THE OUTPUT
<div class='media-container'>
</div>
DEBUGGING ATTEMPTS
echoing the exact file path of a known image in an <img> tag works fine. putting echo'test'; inside the file_exists case does nothing.
--
Solution (Kind of)
So I've used html's onerror before and I found a workaround, though I'd still like to know why I was getting an error. PSA this uses JQuery but javascript works too:
My Solution
<script>
function img2video(el, src) {
$( el ).replaceWith( '<video class="videoClass"><source src="'+src+'" type="video/mp4"></video>' );
}
</script>
<body>
<img style="width:100%" onerror="img2video(this,'<?php echo$pathname;?>')" src="<?php echo$pathname;?>">
</body>
Alright, so here's the final answer I made to best fit the problem using glob:
Javascript:
function img2video(el,src,place) {
if (place=='type') {
$( el ).replaceWith( '<video controls controlsList="nodownload" disablePictureInPicture style="width:100%;object-fit:contain;" preload="auto"><source src="'+src+'" type="video/mp4"></video>');
}
}
PHP:
<?php for ( $i=1; $i <= $limit; $i++) {
$path ="[DIRECTORY]/".$row["id"]."media".$i;
$path = (!empty(glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0])) ? glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0] : false;?>
<div>
<img onerror="img2video(this,'<?php echo$path;?>','type',<?php echo$row["id"];?>,<?php echo$i;?>)" src="<?php echo$path;?>">
</div>
<?php } ?>
I don't know how to mark as duplicate, if someone could help with that. My answer uses Glob_Brace from #Akif Hussain 's response on This Question.

Include directive with page variable doesn't work inside markup

I have some markup such as:
Markup('talk', '<include',
'/\\(:talk:\\)/i',
'MarkupTalk');
function MarkupTalk($m) {
return 'Talk page: (:include {$BaseName}-talk:)'
}
but when I use it, it does nothing!
Example text (:talk:) more text
outputs
<div id="wikitext">
<p>Example text Talk page: more text</p>
almost as if the (:include:) directive is a comment! It seems like (:include:) doesn't work when defined in other markup.
How can I make this work properly?
The reason that this doesn't work properly is that your markup:
talk <include B>=><
is evaluated after one of its dependencies:
{$var} >$[phrase] B=>>
To fix this, you could change when your markup is evaluated:
Markup('talk', '<{$var}',
'/\\(:talk:\\)/i',
'MarkupTalk');
but this can be undesirable if you have any markup that outputs ("depends on") yours. Instead, you can modify your function to use the PageVar() function as noted in PmWiki.PageVariables, like so:
function MarkupTalk($m) {
global $pagename;
$pagename = ResolvePageName($pagename);
return 'Talk page: (:include '. PageVar($pagename, '$BaseName') .'-talk:)'
}
This removes {$var} as a dependency and allows your markup to be safely evaluated after {$var} is.

WP Thumbail not rendered correctly

I'm trying to add a thumbail to a div using the_post_thumbnail() function.
The code I'm using is the following:
<div class="sc-col sc-s12 sc-m3 sc-card sc-card-basic">
<figure>'.the_post_thumbnail(array('370', '188')).'</figure>
</div>
But when the code is rendered in a browser the code becomes (just took a part of the rendered code):
<img width="370" height="182" src="/wp-content/uploads/2016/05/image.png">
<div class="sc-col sc-s12 sc-m3 sc-card sc-card-basic">
<figure></figure>
</div>
As you can see the image is rendered outside the div and figure. My question is why is it doing this? Because now my whole layout is breaking now and, the problem is that I have to use that function else I would have used an other function. Can I somehow rewrite the function so it only returns the src link using add_filter function?
https://developer.wordpress.org/reference/functions/the_post_thumbnail/ shows that the function the_post_thumbnail is designed to actually output something to the page, not return a string.
So change your code to something more like this:
$html = '<div class="sc-col sc-s12 sc-m3 sc-card sc-card-basic">
<figure>';
echo $html;
the_post_thumbnail(array('370', '188'))
$html = '</figure>
</div>';
echo $html;
This solved it for me:
<figure><?php the_post_thumbnail(array('370', '188')); ?></figure>
As staded by #ChrisLear the_post_thumbail() doens't return a string and there for fails.

Using PHP X-Path to extract specific parts of a webpage

I am after a specific value from a webapge; the product name that is in the h1 tag:
<div id="extendinfo_container">
<h1><strong>Product Name</strong></h1>
<div style="font-size:0;height:4px;"></div>
<p class="text_breadcrumbs">
<img src="arrow_091.gif" align="absmiddle"/>
Product Name<img src="arrow_091.gif" align="absmiddle"/>
<strong>Product Name</strong>
<div class="dotted_line_blue">
<img src="theme_shim.gif" height="1" width="100%" alt=" " />
</div>
</div>
This is a poorly structured website with more than one h1 so I cannot simply do getElementById('h1').
I want to be as specific as possible in which element I get and this is the code I have:
$doc = new DOMDocument();
#$doc->loadHTML(file_get_contents('http://url/to/website'));
// locate <div id="extendinfo_container"><a><h1><strong>(.*)</strong></h1></a> as product name
$x = new DOMXPath($doc);
$pName = $x->query('//div[#id="extendinfo_container"]/a/h1/strong');
var_dump($pName->nodeValue);
This is return null. What query do I need to use to get the content I want?
query() returns a DOMNodeList, which doesn't have a nodeValue property. You have to select one element (i.e. the first):
$pName = $x->query('//div[#id="extendinfo_container"]/a/h1/strong')->item(0);
Or iterate over it:
foreach( $pName as $el) {
var_dump( $el->nodeValue);
}
Either one of these will give you access to a DOMNode, which is what you're looking for.
PHP's DOM is VERY picky about the html you load into it. It will barf and refuse to load even slightly malformed documents.
Turn off error supression (#$doc->loadHTML, remove the #) and make sure that it's not puking on this page you're trying to analyze. Otherwise, your XPath query looks fine, and if the document does get loaded/parsed properly, it SHOULD work.
The query works fine. I was accessing the value wrong. Here is the correct way to access the value:
var_dump($pName->item(0)->nodeValue);

Removing HTML comments from DOM

So basically, what im trying to achieve is output data via php within html comments and so it is not rendered.
Then use javascript to remove the comments so it is rendered on screen but in view page source, comments must be still there.
I tried a few solutions mentioned on other stackoverflow posts but nothing did the trick.
Any ideas anyone?
For example: if you view the source code of facebook, their content is in comments but yet its rendered.
<script>big_pipe.onPageletArrive({"phase":1,"id":"pagelet_composer","css":["sbVQp"],"bootloadable":{"legacy:Composer":{"resources":["Q6HMA","sbVQp"]},"legacy:DataSource":{"resources":["Q6HMA"]},"legacy:dom":{"resources":["Q6HMA"]},"legacy:control-textarea":{"resources":["Q6HMA","IRaZg","sbVQp"]}},"resource_map":{"IRaZg":{"type":"js","src":"http:\/\/static.ak.fbcdn.net\/rsrc.php\/v1\/yM\/r\/pc-N6ldw6Ia.js"}},"js":["Q6HMA"],"jscc_map":"({\"j98xJNAPg55OWGAly21\":function(){return new DataSource({\"maxResults\":5,\"queryData\":{\"viewer\":100003192277539,\"filter\":[\"page\",\"app\"],\"context\":\"topics\",\"rsp\":\"mentions\"},\"queryEndpoint\":\"\\\/ajax\\\/typeahead\\\/search.php\",\"bootstrapData\":{\"viewer\":100003192277539,\"filter\":[\"user\",\"friendlist\",\"page\",\"app\",\"group\",\"event\"],\"options\":[\"friends_only\",\"nm\",\"include_subscribed_lists\"],\"token\":\"v7\",\"context\":\"mentions\",\"rsp\":\"mentions\"},\"bootstrapEndpoint\":\"\\\/ajax\\\/typeahead\\\/first_degree.php\",\"token\":\"1332238929-7\"});},\"j98xJNAPg55OWGAly22\":function(){return new Composer($(\"uwgh9l_7\"), {\"xhpc\":\"composerTourStart\",\"endpoint\":\"\\\/ajax\\\/updatestatus.php\",\"formType\":1,\"placeholder\":\"What's on your mind?\",\"buttonLabel\":\"Post\",\"autoscrape\":true,\"barContent\":\"\\u003Cspan class=\\\"uiComposerTagControls friendTaggerIcon\\\">\\u003C\\\/span>\\u003Cspan class=\\\"uiComposerTagControls placeTaggerIcon\\\">\\u003C\\\/span>\",\"disableCache\":true,\"lazyEndpoint\":\"\\\/ajax\\\/metacomposer\\\/attachment\\\/status\\\/status.php\"}, true, JSCC.get('j98xJNAPg55OWGAly21'));},\"j98xJNAPg55OWGAly23\":function(){return new MentionsInput($(\"uwgh9l_8\"));},\"j98xJNAPg55OWGAly24\":function(){return new MetaComposerMessageBox();},\"j98xJNAPg55OWGAly25\":function(){return new TypeaheadMetrics({\"extraData\":{\"event_name\":\"mentions\"}});},\"j98xJNAPg55OWGAly26\":function(){return new Typeahead(JSCC.get('j98xJNAPg55OWGAly21'), {node_id: \"\", ctor: \"ContextualTypeaheadView\", options: {\"autoSelect\":true,\"renderer\":\"compact\"}}, {ctor: \"TypeaheadAreaCore\", options: {}}, $(\"uwgh9l_12\"))}})","onload":["JSCC.get('j98xJNAPg55OWGAly22').init(JSCC.get('j98xJNAPg55OWGAly23'));","JSCC.get('j98xJNAPg55OWGAly24').init($(\"uwgh9l_11\"), JSCC.get('j98xJNAPg55OWGAly23'));"],"content":{"pagelet_composer":{"container_id":"uwgh9l_14"}}});</script>
<code class="hidden_elem" id="uwgh9l_15"><!-- <ul id="boulder_fixed_header" class="uiStream"><li class="mts uiStreamHeader"><span class="plm uiStreamHeaderText fss fwb"></span><div class="uiStreamHeaderChronologicalForm"><div class="uiSelector inlineBlock uiSelectorRight uiSelectorNormal uiSelectorDynamicLabel"><div class="wrap"><a class="uiSelectorButton uiButton" role="button" href="#" aria-haspopup="1" data-length="30" rel="toggle"><span class="uiButtonText">SORT</span></a><div class="uiSelectorMenuWrapper uiToggleFlyout"><div role="menu" class="uiMenu uiSelectorMenu"><ul class="uiMenuInner"><li class="uiMenuItem uiMenuItemRadio uiSelectorOption checked" data-label="SORT"><a class="itemAnchor" role="menuitemradio" tabindex="0" aria-checked="true" href="/?sk=h_nor"><span class="itemLabel fsm">Top Stories</span></a></li><li class="uiMenuItem uiMenuItemRadio uiSelectorOption" data-label="SORT: MOST RECENT"><a class="itemAnchor" role="menuitemradio" tabindex="-1" aria-checked="false" href="/?sk=h_chr"><span class="itemLabel fsm">Most Recent</span></a></li></ul></div></div></div><select><option value=""></option><option value="h_nor" selected="1">SORT</option><option value="h_chr">SORT: MOST RECENT</option></select></div></div></li></ul><div id="pagelet_stream_masher" data-referrer="pagelet_stream_masher"></div><div class="UIIntentionalStream UIStream" id="c4f68733a3e65c9c49002913"><ul class="uiList uiStream uiStreamHomepage translateParent UIIntentionalStream_Content" id="home_stream"></ul><div ><div class="UIIntentionalStream_Error"><div class="pam uiBoxRed"><div class="fsl fwb fcb">This stream is unavailable at this time. Please try again soon.</div></div></div></div><div ><div id="pagelet_stream_pager"></div></div></div> --></code>
They use a system called bigpipe for realtime and faster interface but i dont want to use a realtime system(not for now).
So im trying to do the same thing!
Locate element that holds comments ( E.g. by using document.getElementBydId), and do this for extracting content within comments:
element.innerHTML = element.innerHTML.replace(/<!--((.|\n|\r)*?)-->/g, '$1');
simple use css and set it to display:none; or visibility : hidden;
if it's for seo purposes there's an article that can be read here
http://3n9.org/articles/css-hiding.html
and tbh i really dont understand what your asking for ... since comment already doesnt get rendered onscreen so i assumme you want to hide html onload
Wrap the "commented" code in a div... and toggle visibility (as posted below) :
function toggleVisibility(var v)
{
var vis="hidden";
if (v) vis="visible";
document.getElementById('yourDiv').style.visibility = vis;
}
You will have to get all nodes from the page and then cycle through them looking for nodeType. Check for comments and then use the removeChild property on the nodes parent.

Categories