jquery toggle one div in php while loop - php

I have this While loop in my php code where I echo rows inside one div that acts like a button and when I press that "button" I want to hide/show the connected div with the jQuery function "toggle". I only get it to work so that when I click any of the "buttons" it opens all divs and not just that one that's connected.
<script>
$(document).ready(function(){
$(".scorec").click(function(){
$(".scorematcho").slideToggle('slow');
});
});
</script>
That's the jQuery I'm using at the moment.
<?php $RM = mysql_query("SELECT * FROM score ORDER BY ScoreID DESC LIMIT 3");
while ($ScoreD = mysql_fetch_assoc($RM)) {
$a = $ScoreD["ScoreOne"]; $b = $ScoreD["ScoreTwo"];?>
<div class="scorec" >
<?php if($a>$b){;?><font color="green"><?php }else{?><font color="red"><?php }?>
<div class="scorel"><img src="flags/<?php echo $ScoreD["FlagOne"]; ?>.png" style="float:left;">
<?php echo $ScoreD["TeamOne"]; ?> | <?php echo $ScoreD["ScoreOne"]; ?></div>
<div class="scorem">-</div>
<div class="scorer"><?php echo $ScoreD["ScoreTwo"]; ?> | <?php echo $ScoreD["TeamTwo"]; ?>
<img src="flags/<?php echo $ScoreD["FlagTwo"]; ?>.png" style="float:right;"></div></font>
</div>
<div class="scorematcho" >
<div class="scorematch">
de_dust2
16-2
</div>
<div class="scorematch">
de_nuke
16-2
</div>
<div class="scorematch">
de_dust
16-2
</div>
</div>
<?PHP } session_destroy()?>
That's the HTML/PHP I'm using. The div "scorec" is the "button" and "scorematcho" is the div I wan't to toggle.The text inside "scorematcho" shall be PHP also, just haven't changed it yet. I have searched and tested some things but can't get anything to work properly, I have noticed that some put all their PHP code inside an "echo", why is that and could that be the problem? Hope that's enough information, please tell if not. Also, if you have some other improvements you think I should make to the code, please tell.

I have added this jfiddle Hope it helps!! http://jsfiddle.net/H77yf/
$(".scorec").click(function(){
$(this).next().slideToggle('slow');
});

Related

How to fix a jQuery code looping incorrectly in a PHP foreach loop

I'm trying to loop a piece of jQuery code inside a foreach loop. Each article in the loop have a phone number custom post type related (ACF). At this point the loop works well.
As you see, the jQuery code only replace an image to another while user clicks in order to show the number (Ex : "Display Phone Number" image, becomes "555-555-1234").
The problem is that when I click in any image to display number...all articles show their phone number at the same time. I think is an ID problem in my jQuery code. After two days of searching and testing different codes this problem still not resolved yet.
Any suggestions/tracks will be very welcome !
Thanks
====
Things I have tried :
I have tried to put the jQuery code outside the foreach (same result)
I have tried to change the id image into a class (works better)
I have tried different jQuery functions (replaceWith(), show(), etc)
foreach ($related_posts_articles as $related_post ){
<div class="col-sm-6 col-md-6 col-lg-3 col-xs-12">
<div>
<a href="<?php echo get_permalink($related_post->ID); ?> ">
<?php echo get_the_post_thumbnail($related_post->ID,"square-300",array('class' => 'img-responsive')); ?>
</a>
<div>
<a href="<?php echo get_permalink($related_post->ID); ?>">
<h2>
<?php echo wp_html_excerpt(strip_tags(get_field('acf_titre_mini', $related_post->ID)), 30, '...' ); ?>
</h2>
</a>
<div>
<?php echo wp_html_excerpt( strip_tags(get_field('acf_description_mini',$related_post->ID)), 129, '...' ); ?>
</div>
<!-- START bloc number -->
<?php if( get_field('acf_numero_image', $related_post->ID) ): ?>
<div>
<img class="input_img" src="<?php the_field('acf_btnVoirNum_image', $related_post->ID); ?>" >
<script>
jQuery(document).ready(function($) {
$( ".input_img" ).click(function() {
$( ".input_img" ).attr( "src", "<?php the_field('acf_numero_image', $related_post->ID); ?>" );
});
});
</script>
</div>
<?php endif; ?>
<!-- END bloc number -->
</div>
</div>
</div>
}
Take note of the 'this' Context
When an event fires in jquery the callback function this context is set to the element which the event was fired from.
jQuery(document).ready(function($) {
$(".input_img").click(function() {
// Use `this` to target the event element
$(this).attr("src", "<?php the_field('acf_numero_image', $related_post->ID); ?>" );
});
});
Advice:
You shouldn't generate same jquery code inside each iteration of the for each. Since you're repeating unnecessary code. You can harness HTML data-* attributes to achieve the outcome you seek.
You are giving the class name the same for all images. Also by looping you are adding lot's of scripts. You can add Onclick events to image and create a function and grab the data and do you things. Also, you can add extra attributes to img tag to get your data. Also try to put different ID like below,
foreach ($related_posts_articles as $key=>$related_post ){
<img id="img-<?php echo $key; ?>" onclick="myFunction(this)" class="input_img" src="<?php the_field('acf_btnVoirNum_image', $related_post->ID); ?>" >
}

Php generating divs, then hiding all the divs

Everything works except for the hide portion. I'm simply trying to hide each div as it is being generated, and I need to get control of the divs as well. So I'm guessing that the div id part is very wrong when I'm trying to increment. Please help!
<?php
$counter=0;
foreach ($foo as $key => $value){
$counter++;
?>
<div id="ad<?php $counter;?>">
<?php include("showPage.php");?>
</div>
<script>$("#ad<?php $counter;?>").hide();</script>
<?php
}
?>
Second part of question:
<script>
$(document).ready(function(){
$("#FooButton").click(function(){
if($('div#ad1').is(':visible')){
$("div#ad1").hide();
$("div#ad2").show();
}
});
});
</script>
Yes you need to echo the value like this
echo $counter;
You need to echo out the value of $counter.
Here:
<div id="ad<?php echo $counter;?>">
<?php include("showPage.php");?>
</div>
<script>
$(document).ready(function(){
$("#ad<?php echo $counter;?>").hide();
});
</script>
Update:
After looking at the above solution, I cannot recommend you calling $(document).ready() in a loop. A more efficient solution to this would be to add style display: none to the generated div and not use the javascript here, like follows:
<div id="ad<?php echo $counter;?>" style="display:none;">
<?php include("showPage.php");?>
</div>

Display Terms of service in any place (Joomla/Virtuemart 2.x)

I have some toruble with displaying terms of service.
At the cart page all works fine: http://mtxt.ibroken.ru/component/virtuemart/cart.html?Itemid=0
(bottom link) opens popup with text, generated by
<?php echo $this->cart->vendor->vendor_terms_of_service; ?>
code.
But i have button on the shop page http://mtxt.ibroken.ru/magazin.html (top button at right side), which must display same text...
At present moment text written in /modules/mod_virtuemart_cart/tmpl/default.php file. But how to get it in this file from shop interface by using PHP?
pps. Ugly English, sorry for that :)
You need to modify /modules/mod_virtuemart_cart/tmpl/default.php (or your override) and add this code just after line 3:
vmJsApi::js ('facebox');
vmJsApi::css ('facebox');
$document = JFactory::getDocument ();
$document->addScriptDeclaration ("
jQuery(document).ready(function($) {
$('div#full-tos').hide();
$('a#terms-of-service').click(function(event) {
event.preventDefault();
$.facebox( { div: '#full-tos' }, 'my-groovy-style');
});
});
");
And add this code just after line 53
<div class="show_cart">
<?php
if(!class_exists('VirtueMartModelVendor'))
require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'vendor.php');
$vendor = VmModel::getModel('vendor');
$vendor = $vendor->getVendor();
?>
<br />
<span style="z-index: 0;">
<a href="<?php JRoute::_ ('index.php?option=com_virtuemart&view=vendor&layout=tos&virtuemart_vendor_id=1') ?>" class="terms-of-service" id="terms-of-service" rel="facebox" target="_blank">
<?php echo JText::_ ('COM_VIRTUEMART_CART_TOS_READ_AND_ACCEPTED'); ?>
</a>
</span>
<div id="full-tos">
<h2><?php echo JText::_ ('COM_VIRTUEMART_CART_TOS'); ?></h2>
<?php echo $vendor->vendor_terms_of_service; ?>
</div>
</div>
That shoud do the trick!

jQuery AJAX Refresh after Insert not working

I have a single page website, I have the insert working correctly, but I cannot seem to update the #results div after submit. The values are being inserted into the database just fine and if I hard refresh they are appearing. But not with the jQuery AJAX refresh. I am new to Ajax, so any help would be really appreciated, and any comments on code structure or bad habits, please comment as I am trying to learn the proper way to program.
Here is my code:
$(document).ready(function(){
$("form#addTodo").submit(function(){
alert('hello world'); // ensure function is running
var post_title = $('input#post_title').val(); // take values from inputs
var post_content = $('input#post_content').val();
$.ajax({
type: "POST",
url: "add.php",
data: "post_title=" + post_title + "&post_content=" + post_content,
success: function() {
// alert('success'); // ensure success
$('#results').fadeOut('slow').load('include/results.php').fadeIn('slow');
}
});
$('input#post_title').val(''); // clear form fields
$('input#post_content').val('');
return false;
});
});
Here is the results.php file:
<?php
$sql = $db->query('SELECT id, post_title, post_content FROM posts ORDER BY post_title ASC');
$results = $sql->fetchALL(PDO::FETCH_OBJ);
$count_posts = count($results);
?>
<?php if ( have_posts() == true) : ?>
<div class="accordion" id="accordion_main">
<?php foreach($results as $entry): ?>
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion_main" href="#collapse-<?php echo $entry->id; ?>">
<?php echo $entry->post_title; ?>
</a>
</div>
<div id="collapse-<?php echo $entry->id; ?>" class="accordion-body collapse">
<div class="accordion-inner">
<p class="target"><?php echo $entry->post_content; ?></p>
<p>Edit Delete</p>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<?php else: ?>
<h3>There are no posts to display at this time.</h3>
<?php endif; ?>
This works fine when it is included by the index.php, I just can't get it to refresh after posting the data to the DB.
<?php
require_once 'includes/db.php';
require_once 'includes/functions.php';
?>
<?php get_header(); ?>
<div id="results">
<?php include_once 'includes/results.php'; ?>
</div>
<hr />
<p>Add New Post</p>
<form id="addTodo" action="">
<div>
<label for="post_title">Post Title</label>
<input id="post_title" name="post_title">
</div>
<div>
<label for="post_content">Post Content</label>
<input id="post_content" name="post_content">
</div>
<div>
<button id="submit" type="submit">
Save
</button>
</div>
</form>
<?php get_footer(); ?>
I should mention that I haven't put in form validation yet. Any help is greatly appreciated, thanks.
Why not just return the data from success? and use that to make your html input
success:function(returnedData) {
if (returnedData.status = 'successful') {
//use javascript to append the data for example like
//returnedData.message to make html and insert into your current html
}
}
Note: returnedData has to be pushed out by your php in an json format.
you can find a similar answer to your request if you read this thread that I had recently answered : Jquery Mobile Post to PHP (same page)
But you must make some adaptation for you context ;-) !!
I think that is the unique solution if you're using unique file script
To insert data returned from php file just use $("element id or class").html() function to insert the data or html to specific area of your document

link not working with jquery

Probably a very simple answer, but I cannot seem to find a working solution. I am creating links from a php search script and it generates links based on query. I have written a sample jQuery script to open a div based on a tag being clicked, but when I click link, nothing happen. I cannot see any errors in firebug and would appreciate somke help. Thank you.
UPDATE: Added html and changed mailLink from id to class.
jQuery
$("a").click(function(e) {
e.preventDefault();
$('.mailShow').fadeIn(1500).html('This is the mailShow div');
});
PHP
<?php
while ($row = mysql_fetch_assoc($rsd))
{?>
<div class="each_rec"><?php echo $row['name_usr'];?> <?php echo $row['idcode_usr'];?></div>
<?php
}
if($total==0){ echo '<div class="no-rec">No Record Found !</div>';}
?>
HTML
<div id="content">
<div class="search-background">
<label><img src="loader.gif" alt="" /></label>
</div>
<div id="sub_cont">
<div class="mailShow"></div>
</div>
</div>
Generated HTML from firebug
<div class="each_rec">Demo User DEMO</div>
In jquery you have .mailShow and in PHP you use id="mailLink". You should change .mailShow to #mailLink.
JSFiddle for testing.
JSFIDDLE
Try this code:
$(document).ready(function () {
$(document).on("click","a",function(e) {
e.preventDefault();
$('.mailShow').fadeIn(1500).html('This is the mailShow div');
});
});
<?php
while ($row = mysql_fetch_assoc($rsd))
{?>
<div class="each_rec"><?php echo $row['name_usr'];?> <?php echo $row['idcode_usr'];?></div>
<?php
}
if($total==0){ echo '<div class="no-rec">No Record Found !</div>';}
?>
I see two probable issues:
1. You didn't use $(document).ready(); and put your code outside of it. Then you need to put the above code to docyument ready.
2. You inseert links dinamycaly - from ajax query. Thus you need to use jquery delegates instead.

Categories