PHP jQuery Post - returns too much HTML - php

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'));
}

Related

How do I adjust margin-top attribute depending on length of php title?

I'm building a custom template in Wordpress.
I need the title of the page to auto adjust itself if it is larger than 45 characters.
The title is being pulled from the Wordpress database via PHP.
I am trying to build javascript to do this:
If the length of the title (via php) is < 45 characters: change the css attribute "margin-top" to 111px.
Else change the css attribute "margin-top" to 150px.
Here is what I have so far:
My HTML:
<div class="title-of-page" id="title" style="margin-top:53px">
<?php echo get_the_title($post->post_parent); ?>
</div>
My Javascript:
<script>
if ( <? php strlen(get_the_title($post - > post_parent)) ?> < 45) {
document.getElementById("title").style.marginTop = "111px";
} else {
document.getElementById("title").style.marginTop = "150px";
}
</script>
Ask questions if I'm not being clear enough.
Why javascript?
<?php
$title = get_the_title($post->post_parent);
if (strlen($title)<45) { $mtop ='111px'; } else { $mtop='150px'; }
echo '<div class="title-of-page" id="title" style="margin-top:'.$mtop.';">'.$title.'</div>';
?>
You can do it in PHP only as #Thomas Martin suggested.
However if you are too keen to do it at the Javascript Side.You can do it by .
<script>
var title = document.getElementById('title').textContent;
if(title.length < 45){
document.getElementById("title").style.marginTop = "111px";
}else{
document.getElementById("title").style.marginTop = "150px";
}
</script>

jQuery show div in PHP While loop

I am having a bit of problems trying to show an information in a div tag using jQuery inside the PHP while loop.
My code looks like this:
$i=1;
while($pack = mysql_fetch_array($packs))
{
$pricepack = $price * $pack['refcount'];
$pricepack = number_format($pricepack,2);
if($users > $pack['refcount'] ) {
$contents .= "
<a class='refbutton' style='text-decoration:none;' onclick=\"document.rent.refs.value='{$pack['refcount']}';document.rent.submit(); return false;\" >{$pack['refcount']}</a>
<div id='refinfo' style='display:none;'>
<span style='font-size:18pt;font-weight:bold;' id='refprice'></span><br />
<span style='color:#D01F1E;'>You don't have enough funds for this package.</span>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$('.refbutton').hover(
function() {
$('#refinfo').show();
$('#refprice').text(\"$\"+\"$pricepack\");
},
function() {
$('#refinfo').hide()
}
);
});
</script>
";
$i++;
}
}
The problem is that the code is generating a div next to each anchor element. This will cause this when the mouse hovers:
What I am trying to obtain is this on every button hover:
As you can see in the second picture, there isn't any design errors or mix-ups. How can I obtain this?
Thank you.
You need to start by cleaning up your code. You only need one refinfo div, and only one javascript block. The only thing in your loop should be the refbutton, and that tag should contain all the values needed for the javscript hover and click events to do their business. Look into HTML5 custom data attributes http://html5doctor.com/html5-custom-data-attributes/
Something more like this should work and provide a sounder basis on which to debug layout issues if any remain.
<?php
$i=1;
while($pack = mysql_fetch_array($packs)) {
$pricepack = $price * $pack['refcount'];
$pricepack = number_format($pricepack,2);
if($users > $pack['refcount'] ) {
$contents .= "
<a class=\"refbutton\" data-pricepack=\"{$pricepack}\" style=\"text-decoration:none;\" >{$pack['refcount']}</a>";
$i++;
}
}
?>
<div id="refinfo" style="display:none;">
<span style="font-size:18pt;font-weight:bold;" id="refprice"></span><br />
<span style="color:#D01F1E;">You don't have enough funds for this package.</span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('.refbutton')
.bind('mouseover',function(event) {
$('#refinfo').show();
$('#refprice').text($(this).data("pricepack"));
})
.bind('click',function(event) {
document.rent.refs.value=$(this).text();
})
.bind('mouseout', function(event){
$('#refinfo').hide();
})
;
});
</script>

onclick confirm function with different text from array

I am having an issue with attempting to show different confirm text from an array when using a hyperlink. The text always ends up being from the last confirmation text in the array. I have seen 2 examples on this forum using a function() in a function but I was not able to get this working from viewing the examples.
Here is my code:
echo '
<script type="text/javascript">
function getDetails(message)
{
if (confirm(message))
return true;
else
{
var links = document.getElementsByTagName("a");
for(i=0;i<links.length;i++)
links[i].href = item_NoLink;
}
}
</script>';
foreach ($items as $item)
{
$link = 'http://test_url/mytest.php;report='. $item['id'];
echo '
<script type="text/javascript">
var item_detail = ', json_encode($item['reported_spam']['detail']),'
var item_NoLink = ', json_encode('http://test_url/mytest.php;'),'
</script>
<a id="mylink[]" onclick="getDetails(item_detail);" href="'.$link.'" style="text-decoration:none;">
<img id="myImage" alt="" src="http://test_url/images/reported.gif" title="'.$item['reported_spam']['title'].'" style="position:relative;border=0px;vertical-align:middle;right:5px;" />
</a>';
}
Thanks.
Edit: I figured it out.
#Grant Zhu: Arrays are not written like that in php and one can progress to the next key just using the empty square brackets. You were correct as I did make an err for the image id array and the js variables. Also for php when using single quotes inside echo with single quotes one must use the backslash (unless using php again).
I got it working as such:
echo '
<script type="text/javascript">
var item_NoLink = ', json_encode('http://test_url/mytest.php;'),'
function getDetails(message)
{
if (confirm(message))
return true;
else
{
var links = document.getElementsByTagName("a");
for(i=0;i<links.length;i++)
links[i].href = item_NoLink;
}
}
</script>';
foreach ($items as $item)
{
$link = 'http://test_url/mytest.php?report='. $item['id'];
echo '
<a id="mylink[]" onclick="getDetails(\'',$item['reported_spam']['detail'],'\');" href="'.$link.'" style="text-decoration:none;">
<img id="myImage[]" alt="" src="http://test_url/images/reported.gif" title="'.$item['reported_spam']['title'].'" style="position:relative;border=0px;vertical-align:middle;right:5px;" />
</a>';
}
Thank you.
$link = 'http://test_url/mytest.php;report='. $item['id'];
this code is weird , I think your code might be
$link = 'http://test_url/mytest.php?report='. $item['id'];
You should check the javascript generated and you will find there're multiple declarations of item_detail and item_NoLink. That means you assign the values to the same variables again and again. Of course, the last assignment takes effect in the end.
You can put the detail text directly in the getDetails function. Make sure the text is quoted by '. And you'd better make the id of <a> and <img> unique because that's what id means. I'm not familiar with PHP, check the syntax below if it's correct.
foreach ($items as $item)
{
$link = 'http://test_url/mytest.php;report='. $item['id'];
echo '
<a id="mylink$item['id']" onclick="getDetails(', json_encode($item['reported_spam']['detail']),');" href="'.$link.'" style="text-decoration:none;">
<img id="myImage$item['id']" alt="" src="http://test_url/images/reported.gif" title="'.$item['reported_spam']['title'].'" style="position:relative;border=0px;vertical-align:middle;right:5px;" />
</a>';
}

Problems with "onload" and XHTML Validation

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

Call PHP script inside a function via return

I am working on integrating two wordpress plugins. What I am trying to do is to add this code<?php DisplayStars(get_the_ID()); ?> into a function of another plugin. I tried $html = '<?php DisplayStars(get_the_ID()); ?>';, but php shows errors. Thanks for your help.
function wpbusdirman_post_excerpt($count)
{
$wpbusdirman_gpid=wpbusdirman_gpid();
$wpbusdirman_permalink=get_permalink($wpbusdirman_gpid);
$html = '';
$html .= '<div id="wpbdmlistings"';
$isasticky = get_post_meta(get_the_ID(),'sticky');
if(isset($isasticky) && !empty($isasticky))
{
$isasticky=$isasticky[0];
}
if(isset($isasticky) && ($isasticky == 'approved'))
{
if($count&1)
{
$html .= ' class="wpbdmoddsticky"';
}
else
{
$html .= ' class="wpbdmevensticky"';
}
}
else
{
if($count&1)
{
$html .= ' class="wpbdmodd"';
}
else
{
$html .= ' class="wpbdmeven"';
}
}
$html .='><div class="listingthumbnail">' . wpbusdirman_display_the_thumbnail() . '</div><div class="listingdetails">';
$html .= wpbusdirman_display_the_listing_fields();
$html .= wpbusdirman_view_edit_delete_listing_button();
$html .= '</div><div style="clear:both;"></div></div>';
return $html;
}
The code base you're working in is php. The code you're adding is php. That means, you don't need to add it inside the html, but simply call the function. (You may need an include at the top of the file for the function to work if it's not in this file)
$html .= DisplayStars(get_the_ID());
should be all you need in the call to add the text to the html.
When you do something like this:
<?php return "<?php echo('foo'); ?>"; ?>
Then PHP doesn't know (or care) about what is between the quotation marks - it's just text, as far as it knows. However, you can get PHP to interpret a string by using eval:
<?php
$command = "echo('foo');";
eval($command);
?>
This will cause PHP to print out "foo". But watch out, eval is dangerous - see the note in the PHP manual.

Categories