Refreshing div with ajax loses link to javascript file - php

I have a div that includes shoutbox posts. I'm using jQuery and ajax to change the pages within the div. However, when the page changes, it loses the link to the javascript file so that the next time I try to change the page it actually continues with the link action instead of doing the ajax in the background. Then after that it's back to normal and it alternates back and forth between being linked to the file and not.
Also before, it was rendering the whole page so that my layout was being displayed on the refresh instead of just the shoutbox posts. I'm guessing that finally getting it to refresh without re displaying the whole layout again is what's causing it to lose the connection to the javascript file.
This is the code for the posts. The shoutbox_arrows contains the links to change the page. refresh_me is what I'm loading into my div to refresh the content.
<div id="shoutbox_arrows">
<?php $current_page=s tr_replace( '?', '#', getURI(fullURL())); ?>
<ul class="no_dots">
<li id="first_page"><<
</li>
<li id="previous_page"><
</li>
<li><strong>Pg#<?php if ($page > $last_page) {echo $last_page;} else {echo $_SESSION['shoutbox_page'];} ?></strong>
</li>
<li id="next_page">>
</li>
<li id="last_page">>>
</li>
</ul>
</div>
<div id="shoutbox" class="custom_scrollbar">
<div id="refresh_me">
<?php if (sizeof($shouts)==0 ) { ?>
<p>There are no posts.</p>
<?php } foreach ($shouts as $shout) { foreach ($shout as $k=>$v) { $shout[$k] = utf8_encode($v); if ($k == 'guest') { $shout[$k] = ucwords($v); } } ?>
<div class="post_info">
<div class="left">
<?php if ($shout[ 'user_id']==n ull) {echo $shout[ 'guest'];} else { ?><?php echo ucwords(userinfo($shout['user_id'])->username); ?>
<?php } ?>
</div>
<div class="right">
<?php time_format($shout[ 'created_at']); ?>
</div>
</div>
<p class="post_comment" id="shoutbox_comment_<?php echo $shout['id']; ?>">
<?php echo $shout[ 'comment']; ?>
</p>
<?php if (!$shout[ 'last_edited_by']==n ull) { ?>
<p class="last_edited">Edited by
<?php echo ucwords(userinfo($shout[ 'last_edited_by'])->username); ?>
<?php time_prefix($shout[ 'updated_at']); ?>
<?php time_format($shout[ 'updated_at']); ?>.</p>
<?php } ?>
<?php if (current_user()) { if (current_user()->user_id == $shout['user_id'] or current_user()->is_mod) { ?>
<p class="post_edit"> <span class="edit" id="<?php echo $page; ?>">
<a id="<?php echo $shout['id']; ?>" href="<?php $post_to = '?id=' . $shout['id']. '&uid=' . $shout['user_id']; echo $post_to; ?>">
edit
</a>
</span> | <span class="delete" id="<?php echo $page; ?>">
<a href="<?php $post_to = '?id=' . $shout['id']. '&uid=' . $shout['user_id']; echo $post_to; ?>">
delete
</a>
</span>
<span class="hide" id="<?php echo $page; ?>">
<?php if (current_user()->is_mod) { ?> | <a href="<?php $post_to = '?id=' . $shout['id']. '&uid=' . $shout['user_id']; echo $post_to; ?>">
hide
</a><?php } ?>
</span>
</p>
<?php }} ?>
<?php } ?>
</div>
</div>
This is the page that my ajax request is going to.
<?php
if (isset($data['page'])) {
$_SESSION['shoutbox_page'] = intval($data['page']);
}
$redirect = ltrim(str_replace('#', '?', $data['redirect']), '/');
redirect_to($redirect);
Div that contains the content to be refreshed.
<div id="shoutbox_container">
<?php relativeInclude( 'views/shoutbox/shoutbox'); ?>
</div>
jQuery
$('#shoutbox_arrows ul li a').click(function (event) {
event.preventDefault();
$.post('views/shoutbox/' + $(this).attr('href'), function (data) {
$('#refresh_me').load(location.href + " #refresh_me>", "");
$('#shoutbox_arrows').load(location.href + " #shoutbox_arrows>", "");
});
});
So I guess to clarify the issue:
The shoutbox_container displays posts for the shoutbox. The page is controller by a session that gets passed as a variable to get the correct chunk of posts to show. Clicking on the links in shoutbox_arrows sends an ajax request to a page which changes the session variable. The div that contains the post itself (refresh_me) as well as the arrows (for the links) get refreshed. After changing the page once, the shoutbox is no longer connected to the javascript file so when you click to change the page again, instead of an ajax request, the page itself actually changes to the link.
Any ideas how I can fix this? I've spent a lot of time on this and it's getting rather frustrating. I feel like I could just settle for it as it is now but it's bugging me too much that it's not working exactly how I intend (although generally it works in terms of changing the pages).
Also just a note, I used jsfiddle to tidy up the code but it looks like it did some funky stuff (looking just at $current_page=s tr_replace). lol. So there aren't any syntax errors if that's what you're thinking. ><
Also I was going to set up a fiddle but I don't really know how to handle links in it so it would have been useless.

The issue is that you bind the click handler to the a tags on document ready (the jQuery code you provided). So when you replace the content of #shoutbox_arrows you remove the click handler you previously attached since those original handlers are removed from the DOM along with the original elements.
You need to use the jQuery .on() method and event bubbling. This will attach the handler on a parent element that will not be removed in your content replace and can continue to "watch" for the event to bubble up from it children elements.
Try replacing your jQuery code with this:
$('#shoutbox_arrows').on('click', 'ul li a', function (event) {
event.preventDefault();
$.post('views/shoutbox/' + $(this).attr('href'), function (data) {
$('#refresh_me').load(location.href + " #refresh_me>", "");
$('#shoutbox_arrows').load(location.href + " #shoutbox_arrows>", "");
});
});

For performance, you should add a class to the a, and targeting it directly with $('a.aClass')
Good ways to improve jQuery selector performance?

Related

How do I run my php function through Ajax and loop through the results?

So I am trying to build a simple search function for my website, and I don't want to have to refresh the page to return results. The code that i have here works perfectly, But I don't know how to Implement this using Jquery. I mainly have 2 pages, index.php and library.php
The section from the library.php that handles the search is as follows.
require_once('auth/includes/connect.php');
class MainLib
{
public function search($keyword){
try {
$db = DB();
$query = $db->prepare("SELECT houses.*, users.user_id FROM houses JOIN users ON users.user_id=houses.ownerid WHERE houses.location=:keyword");
$query->bindParam(":keyword", $keyword, PDO::PARAM_STR);
$query->execute();
if ($query->rowCount() > 0) {
return $query->fetchAll(PDO::FETCH_OBJ);
}
} catch (PDOException $e) {
exit($e->getMessage());
}
}
}
And the Section From the index.php that prints the results is as follows
<?php $hdata = new MainLib();
if(isset($_POST[$search])){
$houses = $hdata->search($search); // get user details
foreach($houses as $house){
?>
<div class="single-property-box">
<div class="property-item">
<a class="property-img" href="#"><img src="houses/<?php echo $house->main_image ?>" alt="#">
</a>
<ul class="feature_text">
<?php
if($house->featured=='true'){
?>
<li class="feature_cb"><span> Featured</span></li>
<?php }?>
<li class="feature_or"><span><?php echo $house->gender ?></span></li>
</ul>
<div class="property-author-wrap">
<a href="#" class="property-author">
<img src="dash/auth/users/<?php echo $house->profilepic ?>" alt="...">
<span><?php echo $house->title ?>. <?php echo $house->surname ?></span>
</a>
<ul class="save-btn">
<li data-toggle="tooltip" data-placement="top" title="" data-original-title="Bookmark"><i class="lnr lnr-heart"></i></li>
<li data-toggle="tooltip" data-placement="top" title="" data-original-title="Add to Compare"><i class="fas fa-arrows-alt-h"></i></li>
</ul>
</div>
</div>
<?php }}?>
So How would I accomplish the same result without having to reload the page every time ?
Here's a basic ajax search form setup using jQuery. Note that the search input is in a form with onsubmit="return false" - this is one way to prevent the default form submission which would trigger a page reload.
The button calls a function which gets the value of the search input, makes sure it's not blank, and puts it into an ajax function
The PHP page will receive the search term as $_GET['term'] and do it's thing. In the end, you will output (echo) html from your PHP functions, which the ajax done() callback will put into your search_results div. There are more optimized ways of transferring the data back - maybe a minimal json string that contains just the info you need for results, and your javascript takes it and inflates it into an html template. For large search results, this would be better because it means less data getting transferred and faster results.
function search() {
let term = $('#search_term').val().trim()
if (term == "") return; // nothign to search
$.ajax({
url: "searchFunctionPage.php",
method: 'get',
data: {
term: term
}
}).done(function(html) {
$('#search_results').html(html);
});
// sample data since we dont have the ajax running in the snippet
let html = 'Found 100 results.. <div>result 1</div><div>...</div>';
$('#search_results').html(html);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit='return false;'>
<input type='text' placeholder="Type in your search keyphrase" id='search_term' />
<button type='button' onclick='search()'>Search</button>
</form>
<div id='search_results'></div>

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); ?>" >
}

set active class for dynamically generated links in php

In my application there is a page where I generate dynamic links based on the data from mysql DB. My task is to set a class="active" for the selected link. If the links where static I can give active class using page name like this. But what to do in my case? Is there any way to get this done?
Here is my code:
<div class="select-region clearfix">
<input type="hidden" id="rgnId" name="rgnId">
<input type="hidden" id="hltypId" name="hltypId">
<ul class="nav">
<li>Select your region</li>
<li value="0"><a class="active" id="show_0" onClick="UAEHolydayDetails(0)">All<span class="badge"><?php echo $uaedetailscount?></span></a></li>
<?php
$i=0;
while($rowrgn = $rsltrgn->fetchAssoc())
{
?>
<li><a id="show_<?php echo $rowrgn['rgnId']; ?>" onClick="UAEHolydayDetails(<?php echo $rowrgn['rgnId']; ?>)"><?php echo $rowrgn['rgnName']; ?><span class="badge">
<?php echo $rowrgn['regioncount'];?></span></a></li>
<?php } ?>
</ul>
</div>
can anyone please help me
Edit 1
when I click any of these dynamic links it passes an id to the same page through js and the page will be filled with data from DB based on this paseed id like this:
onClick="UAEHolydayDetails(<?php echo $rowrgn['rgnId']; ?>)"
js:
<script>
function HolytypeDetails(id){
$('#hltypId').val(id);
window.location='uae-holidays.php?hltypId='+id;
}
</script>
in script the page in window.location is the page where the links are generated itself
Of course. It's the same thing. You need to know your active item id and based on this information just chose the item you want.
<?php
$activePageId = 5;
$i=0;
while($rowrgn = $rsltrgn->fetchAssoc())
{
?>
<li <?php if($rowrgn['rgnId'] === $activePageId){ ?>class="active"<?php } ?>><a id="show_<?php echo $rowrgn['rgnId']; ?>" onClick="UAEHolydayDetails(<?php echo $rowrgn['rgnId']; ?>)"><?php echo $rowrgn['rgnName']; ?><span class="badge">
<?php echo $rowrgn['regioncount'];?></span></a></li>
<?php } ?>
You may just use a selector to grab it via the href
Example with jquery:
$('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');

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!

How to link to a specific part in the same page with jquery and php?

I know to link to a part in the same page like :
<a href='#A'>A</a>
<a name='A'>Here is A</a>
But when I designed it with jquery and php, ı have a problem. My design is like :
There are all letters of alphabet. Under the letters, there are there are divs (item_A,item_B,item_c etc...). When the user click K letter for example, page will link to #K div and also #K div display its content.(Because when the site open first, item divs' display are none). But the problem is, although #K (K is just example) K is displayed its content, page did not redirect to #K div. You must scroll by yourself.
Here is the code :
<div class="content_letters">
<ul>
<?php $array_letter = array("A","B","C","Ç","D","E","F","G","H","I","İ",
"J","K","L","M","N","O","P","R","S","Ş","T",
"U","Ü","V","Y","Z");
for ($i=0;$i<27;$i++) {
echo "<li><a id='letter_{$array_letter[$i]}'
href='#letter_{$array_letter[$i]}'>{$array_letter[$i]} | </a></li>";
}
?>
</ul>
</div>
<?php
for ($i=0;$i<27;$i++) {
?>
<div class="content_letter_block">
<div class="text">
<div class="show_hide">
<a class="button" id="
<?php echo 'button_letter_'.$array_letter[$i]; ?>">SHOW/HIDE</a>
</div>
<a name="<?php echo "letter_".$array_letter[$i].'">';?>
<?php echo $array_letter[$i]; ?></a> starts from here</div>
</div>
</div>
<?php } ?>
<div style='display:none' id='<?php echo "item_".$array_letter[$i];?>'>
Here is item...
</div>
Here is the jquery code :
$(document).ready(function() {
// target everything with IDs that start with 'button_letter'
$("[id^='button_letter']").click(function () {
// split the letter out of the ID
// of the clicked element and use it to target
// the correct div
$("#item_" + this.id.split("_")[1]).toggle();
});
$("[id^='letter']").click(function () {
$("#item_" + this.id.split("_")[1]).show();
});
});
Don't have the time to see all your code, but can't use a scrollTop() method ?
See here.
To scroll with jQuery to a specific ID in your page, use
$('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
You can specify an anchor in your url as well.
<a href="your-page.html#k" />
When you click the link you will be taken to that page and the document will scroll automatically to the position of <a name="k">

Categories