Problems with "onload" and XHTML Validation - php

My name is Manuel, I am a web design student and am starting to take my first steps with web design. Recently I tried to validate
this site:
http://accesosnormalizados.com
I used the W3C validator, at first I found about 30 errors, and can correct them all except one that says: 'there is no attribute
"onload"'.
Apparently not support XHTML onload tag, and I use a Joomla extension called Vertical Menu using onload. This is a free extension and works well but I have found it has some bugs, especially when validating the website.
This is the PHP code for extension:
get( 'menutype', 'mainmenu' );
$qry = "SELECT id, name,parent, link,type,browserNav FROM #__menu WHERE menutype = '".$menutype."' AND published = 1 ORDER BY ordering";
$database->setQuery($qry);
$rows = $database->loadObjectList();
if(isset($GLOBALS['vertical_menu'])) $GLOBALS['vertical_menu']++;
else $GLOBALS['vertical_menu'] = 0;
function getMenuChildList($rows, $parentId) {
$childRows = array();
foreach ($rows as $row) {
if ($row->parent == $parentId) {
$childRows[] = $row;
}
}
return $childRows;
}
function drawVerticalMenu($rows, $showsubcats, $parentId = 0) {
$categories = $showsubcats || !$parentId ? getMenuChildList($rows, $parentId) : array();
if ($parentId) {
if (!count($categories)) {
echo '';
return;
} else echo '';
echo '';
} else echo '';
echo '';
foreach ($categories as $category) {
$link = $category->link. (preg_match("/^http:\/\/|^https:\/\//",$category->link)? "" : '&Itemid='.$category->id);
$blank = $category->browserNav? ' target="_blank" ' : ' ';
echo 'id.'" class="menu">'.$category->name.' ';
drawVerticalMenu($rows, $showsubcats, $category->id);
}
echo '';
if ($parentId && count($categories)) echo '';
}
$document = &JFactory::getDocument();
$document->addScript('https://ajax.googleapis.com/ajax/libs/dojo/1.5.0/dojo/dojo.xd.js');
$document->addScript('modules/mod_vertical_menu/script/menu.js');
$document->addStyleSheet('modules/mod_vertical_menu/style/menu.css');
$document->addCustomTag('
div#MenuContainer'.$GLOBALS['vertical_menu'].' table#VerticalMenu'.$GLOBALS['vertical_menu'].' {
width: '.$params->get('categorymenu_width', 150).'px;
opacity: '.$params->get('categorymenu_out', 0.8).';
FILTER: progid:DXImageTransform.Microsoft.Alpha(Opacity='.($params->get('categorymenu_out', 0.8)*100).');
}
');
echo '';
drawVerticalMenu($rows, $params->get('show_subcats', 1));
echo 'get('categorymenu_out', 0.8).',over : '.$params->get('categorymenu_over', 1).',duration : '.$params->get('categorymenu_fade', 300).',id : '.$GLOBALS['vertical_menu'].',width : '.$params->get('categorymenu_width', 150).'});" alt=""/>';
echo '';
?>
The problem is at the end:
echo '';
drawVerticalMenu($rows, $params->get('show_subcats', 1));
echo 'get('categorymenu_out', 0.8).',over : '.$params->get('categorymenu_over', 1).',duration : '.$params->get('categorymenu_fade', 300).',id : '.$GLOBALS['vertical_menu'].',width : '.$params->get('categorymenu_width', 150).'});" alt=""/>';
echo '';
?>
I think the extension uses the onload event to display the sub-menus when the user moves the mouse pointer over it.
What I want is to replace the onload with other event handler or some other label that is supported by XHTML and that is as similar to onload.
I would appreciate your help ...

You can remove the onload attributes and then add some simple javaScript to your page to run some functions when the page finishes loading.
It would look something like this:
<script>
window.onload=function(){
new WW.VerticalMenu({out : 1,over : 1,duration : 300,id : 0,width : 180}); // example of one of the functions being run
};
</script>
Good luck with your studies

It appears the source comes out like this right
<img src="/modules/mod_vertical_menu/images/center.gif" style="display:none" onload="new WW.VerticalMenu({out : 1,over : 1,duration : 300,id : 0,width : 180});" alt=""/>
As that looks like imho an unsavoury method of instantiating the menu I would try and loose that attribute completely by removing the offending php echo section and instead add javascript to load
as this is using dojo maybe this will help -- sorry I do not use dojo
http://mail.dojotoolkit.org/pipermail/dojo-interest/2012-May/066106.html
so php wise this would be
echo '<img src="modules/mod_vertical_menu/images/center.gif" style="display:none" alt=""/>'; echo '</div>';
echo "<script>" ."javascript or dojo script here ".</script>"
I would even suggest removing the image and using the window onload advocated below if you can

Related

How to insert php code inside javascript

Kindly pls have a look at the code below ! Its working perfectly except the php code is not giving any output. When i insert the output of the php , the script work perfectly.
<script type="text/javascript">
function LoadVideoBar() {
var videoBar;
var barContainer = document.getElementById("videoBar");
var options = {
largeResultSet : false,
horizontal : true,
autoExecuteList : {
cycleTime : GSvideoBar.CYCLE_TIME_SHORT,
cycleMode : GSvideoBar.CYCLE_MODE_LINEAR,
executeList : [ "<?php $cat = get_the_category(); $cat = $cat[0]; echo $cat->cat_name; echo "-"; echo wp_title(); ?> "]
}
}
new GSvideoBar(
document.getElementById("videoBar"),
document.getElementById("videoPlayer"),
options
);
}
GSearch.setOnLoadCallback(LoadVideoBar);
When i replace the php code
<?php $cat = get_the_category(); $cat = $cat[0]; echo $cat->cat_name; echo "-"; echo wp_title(); ?>
with some text like : categoryname-title name
The script works perfectly.
Can somebody help me out with this small issue ...
Many Thanks in Advance!
If you ever need to pass data between the two. Put the PHP value into a hidden field. then read it like you did with bar container
Save the value from PHP:
<?php $cat = get_the_category(); $cat = $cat[0]; ?>
<input id="executeListValue" type="hidden"
value="<?php echo $cat->cat_name."-".wp_title();?>" >
read it in js:
var executeListValue = document.getElementById("executeListValue").value;
//...
autoExecuteList : {
cycleTime : GSvideoBar.CYCLE_TIME_SHORT,
cycleMode : GSvideoBar.CYCLE_MODE_LINEAR,
executeList : executeListValue
}
if the php code is replaced and the script works fine means php is having some error while executing. can you please try to see the source code of the html page. this may be happening because of some php error happening and those error message string could be making some syntax error to javascript.
try to put the php code outside the javascript tag and see the output generated from it.
<?php
$cat = get_the_category();
$cat = $cat[0];
$output= $cat->cat_name."-".wp_title();
?>
and then try to print the output in the javascript.
executeList : [ "<?php print $output; ?>"]
}
by this way you can see if any php error is encountered.
Replace "-" with '-' in Javascript code in line:
[ "<?php $cat = get_the_category(); $cat = $cat[0]; echo $cat->cat_name; echo "-"; echo wp_title(); ?> "]

PHP Display option depending on value

I am editing a part of a script that displays gender of a person but trying to add additional options.
The form that saves the information saves it as a value.
In my lang file this is what i have got related to the part i am trying to change :
$LNG['powner'] = 'Pet Owner';
$LNG['dog'] = 'Dog';
$LNG['cat'] = 'Cat';
$LNG['rabbit'] = 'rabbit';
The part of the code im trying to display is
((!empty($profile['gender'])) ? '<div class="sidebar-list">'.$LNG['ttl_gender'].':
<strong>'.(($profile['gender'] == 1) ? $LNG['powner'] :($profile['gender'] == 2) ?
$LNG['cat'] : ($profile['gender'] == 3) ? $LNG['rabbit'] : $LNG['rabbit']).'</strong>
</div>' : '').'
But it will only display cat or rabbit ...
I am thinking that the code is set to be one or the other because this works :
((!empty($profile['gender'])) ? '<div class="sidebar-list">'.$LNG['ttl_gender'].'
: <strong>'.(($profile['gender'] == 1) ? $LNG['dog'] : $LNG['cat']).'</strong></div>'
: '').
after the code if follows
'.((!empty($profile['website'])) ? '<div class="sidebar-list">'
.$LNG['profile_website'].': <strong><a href="'.$profile['website'].
'" target="_blank" rel="nofllow">'.$LNG['profile_view_site'].'</a>
</strong></div>' : '').'
Your code could be re-written to say:
if(!empty($profile['gender']) {
echo '<div class="sidebar-list">'.$LNG['ttl_gender'];
} else {
echo "<strong>";
if($profile['gender'] == 1) {
echo $LNG['powner'];
} else {
if($profile['gender'] == 2) {
echo $LNG['cat'];
}
else {
if($profile['gender'] == 3){
echo $LNG['rabbit'];
} else {
echo $LNG['rabbit'];
}
}
}
}
As you see the code using shorthand If/Else statements is confusing to read, and can lead to mistakes. Re-write your functionality in more readable way, and you will prevent errors, and confusion with regards to what the actual conditions should be.
I'm assuming that the problem you're having is that the users you're testing this on are either gender 2 or 3, and never 1.

PHP jQuery Post - returns too much HTML

I have a problem when using jQuery Post, the PHP returns all the HTML of the page up to the newly created HTML, rather then just the HTML that is output by the PHP.
As an example say the php outputs: '<div>Some Content</div>'
Then the jQuery Post returns: '<html><head>...all the head content...</head><body>...other content...<div>Some Content</div>'
Here's the jQuery (link to full code: http://pastebin.com/U7R8PqX1):
jQuery("form[ID^=product_form]").submit(function() {
var current_url = js_data.current_url;
form_values = jQuery(this).serialize();
jQuery.post(current_url+"?ajax=true", form_values, function(returned_data) {
jQuery('div.shopping-cart').html(returned_data);
}
});
return false;
});
And here's the PHP (version 5.3.6 - link to full code: http://pastebin.com/zjSUUbmL):
function output_cart()
{
ob_start();
echo $this->output_cart_html();
$output = ob_get_contents();
ob_end_clean();
echo $output;
exit();
}
function output_cart_html() {
if (!isset($_SESSION['cart_items']))
{
$output = '<div class="cart_content faded">BASKET - Empty</div>';
return $output;
} else {
$total_items = 0;
$total_items = 0;
$items_in_cart = $_SESSION['cart_items'];
// work out total price and total items
foreach ($items_in_cart as $item_in_cart) {
$total_items += $item_in_cart['quantity'];
$total_price += floatval($item_in_cart['updated_price']*$item_in_cart['quantity']);
}
$template_url = get_bloginfo('template_directory');
$output = '';
$output_price = $dp_shopping_cart_settings['dp_currency_symbol'].number_format($total_price,2);
if($total_items == 1){ $item_text = ' Item'; } else { $item_text = ' Items'; }
$output .= $total_items . $item_text;
$output .= ' <span class="bullet"></span> Total '.$output_price;
// empty cart btn
$output .= '<form action="" method="post" class="empty_cart">
<input type="hidden" name="ajax_action" value="empty_cart" />
<span class="emptycart"> <img src="'.$template_url.'/images/empty.png" width="9" height="9" title="Empty Your Items" alt="Empty Your Items" />Empty Your Cart</span>
</form>';
// check out btn
$output .= ' <span class="bullet"></span> <span class="gocheckout">'.$this->output_checkout_link().' </span>';
return $output;
}
}
You need to check if the form has been posted yet with the PHP. To do this, just check if the 'ajax' parameter is there, or send another $_GET variable if you wish (by adding &anotherparementer=1 to the end of the jQuery post URL). Example:
<?php
if(isset($_GET['ajax'])) {
//your PHP code here that submits the form, i.e. the functions that you have, etc.
}
else {
?>
<html>
<head>
head content here...
</head>
<body>
body content here...
</body>
</html>
<?php
}
?>
I hope this helps.
Ok it turns out my problem was with the way Wordpress processes AJAX requests. The plugin I was building on top of was using AJAX but didn't have these issues (I'm not sure why maybe because they were using eval), so I hadn't realised there was a correct way of using AJAX with Wordpress. Here's a bunch of information if anyone else has similar problems:
http://codex.wordpress.org/AJAX_in_Plugins
http://byronyasgur.wordpress.com/2011/06/27/frontend-forward-facing-ajax-in-wordpress/
(this one really helped me out, a very simple example that I was able to adapt)
-- sorry I couldn't post more links because I'm too new on this site, but check out the links at the bottom of the first link above, especially the '5 Tips'.
As I'm using classes I instantiated the class from the index file of my plugin with this:
if ($_POST['action'] === 'action_name') {
$class_obj = new \namespace_name\class();
add_action('wp_ajax_action_name', array($class_obj, 'method_name'));
add_action('wp_ajax_nopriv_action_name', array($class_obj, 'method_name'));
}

Why is my PHP variable created by my xpath query is throwing an "Object of class DOMAttr could not be converted to string" fatal error?

So I started a question to figure out why my PHP code that is meant to grab the only MP3 URL that exists within each of my Post contents on my Wordpress installation for a custom use of the content here >> Why doesn't my properly defined variable evaluate for length correctly (and subsequently work in the rest of my code)?
I have made several edits and updates and now need to re-formulate both the question and the context. User mrtsherman points out that based on the order I have written code, that I redefine $doc but don't load that into $xpath, however when I try to adjust this my code throws the fatal error "Object of class DOMAttr could not be converted to string" on the line at the very end where I echo the variable $BEmp3s, the end result of all this. Does this mean it cannot convert the attributes to a string I think??
I know I am soo close to the solution here it's nearly killing me but I also think I have been looking at this wayy too much and for too long. Any insight is golden at this point! Here is my code that branches correctly throughout now:
<?php
// Start MP3 URL
$doc = new DOMDocument();
$doc->strictErrorChecking = FALSE;
$xpath = new DOMXpath($doc);
// End MP3 URL
$a = 1;
if (have_posts()) :
while ( have_posts() ) : the_post();
?>
<?php
$BEpost_content = get_the_content();
if (strlen($BEpost_content) > 0) {
echo "<div id='debug_content'>get_the_content has something</div>";
} else {
echo "<div id='debug_content'>BEpost_content is empty</div>" ;
};
$success = $doc->loadHTML($BEpost_content);
$xpath = new DOMXpath($doc);
if ($success === FALSE) {
echo "<div id='debug_loadcontent'>loadHTML failed to load post content</div>";
} else {
$hrefs = $xpath->query("//a[contains(#href,'mp3')]/#href");
if ($hrefs->length > 0) {
echo "<div id='debug_xpath'>xpath found something</div>";
} else {
echo "<div id='debug_xpath'>xpath found nothing</div>";
};
$BEmp3s = $hrefs->item(0);
};
?>
<script type="text/javascript">
var myCP<?php echo $a; ?> = new CirclePlayer("#jquery_jplayer_<?php echo $a; ?>",
{
mp3: "<?php echo $BEmp3s; ?>"
}, {
cssSelectorAncestor: "#cp_container_<?php echo $a; ?>",
volume: 0.5
});
</script>
mp3: "<?php echo $BEmp3s->value; ?>"
Try using value?

Ajax request and jquery conflict

I have gallery.php that loads images with src path from a database.
I also have an external main.js that detects a click on a .thumbnail.
Everything works flawlessly until I load different images (another category of images, another set) via ajax. (the load() function of jquery) Everything shows just fine, but a problem with javascript appears.
After that, I can't retrieve the src attribute of my thumbnail. Here's what I mean.
BEFORE AJAX
Category 1 pictures/thumbnails
<a class="thumbnail"><img src="ressources/images/image1Small.jpg" /></a>';
<a class="thumbnail"><img src="ressources/images/image2Small.jpg" /></a>';
<a class="thumbnail"><img src="ressources/images/image3Small.jpg" /></a>';
And so on...
AFTER AJAX CALL
Category 2 pictures/thumbnails
<a class="thumbnail"><img src="ressources/images/image4Small.jpg" /></a>';
<a class="thumbnail"><img src="ressources/images/image5Small.jpg" /></a>';
<a class="thumbnail"><img src="ressources/images/image6Small.jpg" /></a>';
As you can see, everything is like before. The a tag has the same class as the old est of pictures. But when I call the function containing :
var path = $(this).children().attr("src");
It now returns : undefined instead of ressources/images/imageXSmall.jpg
I tried checking if $(this) returned something else after, but no success.
I was wondering if when an external .php file was loaded via jquery.load(), the link between those newly created <a class="thumbnail"> tags and main.js were lost. Like if I had to reload main.js after the jquery.load() function. Or something like that...
Thank you!
EDIT Here's the code:
When clicking on a link to different
category
.linkSubCat being different categories
$(".linkSubCat").click(function(){loadImages($(this).attr("id"));});
then
function loadImages(pCategory) {
switch (pCategory) {
case "subCat00":
$(".pics").load('loadImages.php',{category:0});
break;
case "subCat01":
$(".pics").load('loadImages.php',{category:1});
break;
case "subCat02":
$(".pics").load('loadImages.php',{category:2});
break;
case "subCat03":
$(".pics").load('loadImages.php',{category:3});
break;
default:
$(".pics").load('loadImages.php',{category:0});
break;
}
}
loadImages.php
<?php
$connection = mysql_connect("localhost","root", "") or die("Error Connecting : " . mysql_error());
if (!mysql_select_db("taktak")) die('Error connecting to database : ' . mysql_error());
function createThumbPHP() {
if(isset($_POST['category'])) {
if($_POST['category'] == 0){
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 0");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
}elseif($_POST['category'] == 1){
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 1");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
}elseif($_POST['category'] == 2){
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 2");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
}elseif($_POST['category'] == 3){
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 3");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
}
return $thumbHtml;
}
else {
$errorMSG = "Error Loading Images";
return $errorMSG;
}
}
echo createThumbPHP();
?>
So everything does what it's supposed to do. Here'sthe problem. This javascript code in main.js :
$(".thumbnail").click(
function(){
$('#imageBig img').remove();
var path = $(this).children().attr("src");
var newPath = path.substring(0, path.length-9);
var newPath2 = newPath += ".jpg";
var imageLoad = new Image();
$(imageLoad).load(function () {
if (--imageLoad == 0) {
// ALL DONE!
}
// anything in this function will execute after the image loads
$('#loader').hide();
var newImg = $('<img />').attr('src',$(this).attr('src'));
$('#imageBig').append( $(newImg) ); // I assume this is the code you wanted to execute
})
.attr('src',newPath2);
}
)
It removes the img in #imageBig, but doesn't seem to get the path of $(this).children().attr("src"); This script worked perfectly before I loaded different thumbnails (even with the same setup (classes, order, ...))
Try using the jQuery "live" event binding, eg
instead of this
$(".thumbnail").click(
use this
$('.thumbnail').live('click',
When using the regular event binders (eg $.click()), the handler is only bound to those elements matched at the time of the call. When you load new elements via AJAX, these will not be bound.
From the jQuery manual
Attach a handler to the event for all elements which match the current selector, now and in the future.

Categories