wordpress jQuery ajax loads unwanted duplicate posts - php

I will try to explain the best I can. Basically I have a grid (masonry) of items and I want to append ajax loaded content (wordpress single.php post) inside each grid div (red).
I have a div class called ajaxcontainer inside each red div that I populate with content. When I click the a href trigger content gets appended as it should, this works once but when I click another item in the grid the old ajaxcontainer gets populated with new content from that href. Basically duplicating.
I want the old ajaxcontainer to keep the old content even though I click another item.
HTML
<article style="background:<?php echo $color ?>;" id="post-<?php the_ID(); ?>"
<?php post_class($classes); ?>>
<div class="hover">
<h2><?php echo $head ?></h2>
<p class="tags"><?php echo $tagsstring; ?></p>
<?php echo $url ?>
<a class="trick" rel="<?php the_permalink(); ?>" href="<?php the_permalink();?>">goto</a>
</div>
<div class="thumbnail <?php echo $paddingstring?>" style="background-image:url(<?php echo $thumbnail[0] ?>);">
</div>
</article><!-- #post-## -->
What I have right now:
$.ajaxSetup({
cache: false,
success: function (result, status, xhr) {
// not showing the alert
console.log('success');
var $this = jQuery(this)
$('.ajaxcontainer', $this).hide().fadeIn();
},
beforeSend: function () {
console.log('beforesend');
$(".ajaxcontainer").html("loading...");
},
complete: function (xhr, stat) {
// hide dialog // works
}
});
$(".trick").each(function () {
$(this).on("click", function (e) {
$(this).parents('.item').append("<div class='ajaxcontainer'>hello world</div>")
var post_link = $(this).attr("href");
$(".ajaxcontainer").load(post_link + ' #content');
return false;
});
});
Any help is appreciated :)

I maybe wrong, but from what I see, if you have duplicated content, next() could help.
Something like $(this).parents('.item').next().append("hello world") in the function.

Related

Data attribute only returning first value

I'm trying to get the body of my page to change color when hovering over some list items. Each list item has its own color stored in a data attribute, which I can see in the chrome inspector. The code is doing what I'd like, but returning only the first color in the list for every item, when I want the body to be the color of each list item.
HTML:
<ul class="menu">
<?php foreach($page->children() as $subpage): ?>
<li id="tesq" data-color="<?= $subpage->color() ?>">
<a href="<?= $subpage->url() ?>">
<?= html($subpage->title()) ?></a>
</li>
<?php endforeach ?>
</ul>
jQuery:
$(function() {
$('li').hover(function() {
$("body").css('backgroundColor', function () {
return $("#tesq").data('color')
});
}, function() {
$("body").css('backgroundColor', 'lightgrey')
});
})
Any help much appreciated
In your current code, you are trying to get data attribute from the entire collection so it will return the data attribute value of the first element among the collection.
In addition to that use class for a group of elements instead of the id(id should be unique in the context - $("#tesq") will select only the first element).
So do it based on the hovered element, where you can use this inside the event handler callback to refer the eleemnt.
PHP :
<ul class="menu">
<?php foreach($page->children() as $subpage): ?>
<li class="tesq" data-color="<?= $subpage->color() ?>">
<a href="<?= $subpage->url() ?>">
<?= html($subpage->title()) ?></a>
</li>
<?php endforeach ?>
</ul>
JQUERY :
$(function() {
$('.tesq').hover(function() {
var $this = $(this);
$("body").css('backgroundColor', function () {
return $this.data('color')
});
}, function() {
$("body").css('backgroundColor', 'lightgrey')
});
})
The callback is completely unnecessary here and you can avoid it.
$(function() {
$('.tesq').hover(function() {
$("body").css('backgroundColor', $(this).data('color'));
}, function() {
$("body").css('backgroundColor', 'lightgrey')
});
})

AJAX in PHP function is applying to every next instance of the function

Here I have an .ajax function within a PHP function, like this:
function phpFunction($ID) {
print "<script>
$('.uparrow').click(function(){
request = $.ajax({
etc... the rest isn't important.
Anyway, the class .uparrow is an html element that runs this .ajax function when clicked. The other thing you should know is that this function: phpFunction() is called a few times in the document, like this:
phpFunction(1)
phpFunction(2)
phpFunction(3)
However, the problem is that when I load phpFunction(), and I click on the .uparrow element, the .ajax call is made on behalf of each instance of phpFunction() that follows the one whose element I clicked on.
So if I clicked on the .uparrow of phpFunction(1), I would also be virtually clicking on the .uparrows of phpFunction(2) and phpFunction(3). Essentially, I need .uparrow to just be a local class that only applies to the instance of phpFunction() that is currently being called.
The only solution I could think of is to replace .uparrow's class name with something unique to each call of this function. The only difference between each instance of phpFunction() is their input $ID and I was thinking I could redefine .uparrow as:
class = '$ID.uparrow'
or
class = $ID + 'uparrow'
But that doesn't work. So how do I make sure that when I click on .uparrow within phpFunction(1), that the .ajax function only gets called that one time?
This is pretty confusing to explain and probably to understand, so please tell me if there's something that needs elaboration.
Let's say you have a list of elements, and when you click one of them, you want to do an ajax call.
click me
click me
<script>
$(function(){ //on DOM ready
$('.uparrow').on('click', function(){
//do ajax call
$.ajax({
url: 'url here'
type: 'post|get'
data: $(this).attr('data-id'), // you only send the ID of the clicked element
... callbacks, etc
})
});
})
</script>
Now you only have a function that makes an ajax call and takes the parameter to send from the element you clicked.
I hope this is what you wanted to achieve
Try something like this
$('[class="uparrow"]').click( function () {
var request = $.ajax({
// Your ajax call
});
});
this will execute ajax on the clicked element with .uparrow class
HTML
<a class="uparrow" href="#" data-ajax="I'm the first element">Click Me</a>
<a class="uparrow" href="#" data-ajax="I'm the second element">Click Me</a>
<a class="uparrow" href="#" data-ajax="I'm the third element">Click Me</a>
JS:
$('[class="uparrow"]').click(function () {
var currentAjax = $(this).data('ajax')
console.log(currentAjax);
});
And the DEMO
Do not call your php function multiple times. Just one time is sufficient.
Modify the markup of your .uparrow element to include the id like so:
<a class="uparrow" data-id="<?php echo $id; ?>" href="#">TextM/a>
Then re-write your php function like so:
function phpFunction() { /* no need to pass the ID */ ?>
<script>
$(function(){
$(document).on('click', '.uparrow', function(){
$.ajax({
url: 'URL',
type: 'POST'.
data: $(this).attr('data-id')
})
});
})
</script>
<?php } ?>
Call your phpFunction like so:
phpFunction();
UPDATE
<!doctype html>
<html>
<head>
<title>trop</title>
<meta charset='utf-8'>
<link rel='stylesheet' href='css/postStyle.css' />
<link href='http://fonts.googleapis.com/css?family=Exo+2:400,300,200|Homenaje&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel='shortcut icon' href='http://icons.iconarchive.com/icons/visualpharm/icons8-metro-style/256/Music-Note-icon.png'>
<script src='../jquery.js'></script>
<script type='text/javascript' src='../script.js'></script>
</head>
<body>
<?php
$ids = array(1,2,3); // IDs of the posts you want
$result = mysql_query("SELECT * FROM all_posts WHERE ID IN($ids)");
while ($data = mysql_fetch_array($result)){
?>
<div class='post' style='width:470px'>
<h3><?php echo $data['Title']; ?></h3>
<div class='date'><?php echo $data['DateTime']; ?></div>
<iframe width='470' height='300' src='http://www.youtube.com/embed/WF34N4gJAKE' frameborder='0' allowfullscreen></iframe>
<p><?php echo $data['Body']; ?></p>
<div class='postmeta1'>
<p><a href='<?php echo $data['DownloadLink']; ?>' target='_blank'>DOWNLOAD</a></p>
</div>
<div class='verticalLine' style='height:39px'></div>
<div class='postmeta2'>
<p class='uparrow' data-id="<?php echo $data['id']; ?>">▲</p>
<div class='votes'>3</div>
<p class='downarrow'>▼</p>
</div>
<div class='verticalLine' style='height:39px'></div>
<div class='postmeta3'>
<div class='tags'>
<p><?php echo $data['Tags']; ?></p>
</div>
</div>
</div>
<?php } ?>
<script>
var request;
$('.uparrow').click(function(){
request = $.ajax({
url: 'votesHandler.php',
type: 'post',
data: { add : '1', ID : $(this).attr('data-id') }
});
request.done(function (response, textStatus, jqXHR){
alert('Voted!');
});
request.fail(function (jqXHR, textStatus, errorThrown){
alert(
'Oops, something went wrong'
);
});
request.always(function () {
alert('Done.');
});
});
</script>
</body>
</html>

Opening post in popup by clicking on it's shorter version

Hi I need to create a simple popup function for wordpress site.
I got loop that is running and showing posts properly. Post when clicked should appear in popup. What I;ve got so far. Apart from adding fancybox to do it's job.
<a class="modalbox" rel="<?php echo $post->ID; ?>" href=" http://localhost/makijaz/?page_id=12">
<article> ...Wordpress post </article>
I got the one beneath from other thread, but it's not working.
$(".modalbox").on("click", function() {
var postId = $(this).prop("rel");
$(this).fancybox();
});
href in is directing to page with template with other loop. Need to Simply gram PostID (it's in rel of an ) and put it into other loop for showing in popup.
<?php
/*
Template Name: Ajax Post Handler
*/
?>
<?php
$post = get_post($_GET['id']);
?>
<?php if ($post) : ?>
<?php setup_postdata($post); ?>
<div class="whatever">
<h2 class="entry-title"><?php the_title() ?></h2>
<div class="entry-content">
<?php the_content(); ?>
</div>
</div>
<?php endif; ?>
Hopefully, I've made myself clear.
I'm guessing your page template doesn't have a get_header and get_footer so in your example scripts won't load.
<?php
/*
Template Name: Your Temp Name
*/
get_header(); ?>
If you want to pass the post id so $post = get_post($_GET['id']); can fetch it, you could try
jQuery(document).ready(function ($) {
$(".modalbox").on("click", function (e) {
e.preventDefault();
var postId = $(this).prop("rel");
$.fancybox.open({
href: this.href + "&id=" + postId,
type: "ajax"
});
});
});
See JSFIDDLE

How to integrate AJAX to avoid page redirection of PHP CMS

I have used a CMS built with PHP and MySQL. It works great and I have fully customized it to my liking. The only thing now to do is make a more efficient way of loading the data. When a user wants to select an article I want the browser to stay on the same exact page/url without reloading or redirecting. Here is a demo of the CMS: DEMO LINK
For example, the above line of code was exerted from the homepage.php script. It is an anchor tag for the user to select to view the whole content of a particular article, which was only partially displayed in the homepage. When this link is clicked, the user is directed away from the homepage and taken to the article's specific URL. How can I get the full article content page to load inside of the homepage and hide the original homepage content to avoid the page redirect problem. Is this something that can be done with this particular CMS? I can provide any PHP script from the CMS if needed. Thanks in advance.
ARCHIVE.php SCRIPT:
<?php foreach ( $results['articles'] as $article ) { ?>
<li>
<h2>
<span class="pubDate"><?php echo date('j F Y', $article->publicationDate)?></span><br><?php echo htmlspecialchars( $article->title )?>
</h2>
<p class="summary">
<?php if ( $imagePath = $article->getImagePath( IMG_TYPE_THUMB ) ) { ?>
<a href=".?action=viewArticle&articleId=<?php echo $article->id?>">
<div class="floated_child0" style="background-repeat:none; background-image:url('<?php echo $imagePath?>');"></div></a>
<?php } ?>
<?php echo htmlspecialchars( $article->summary )?> (more)
</p>
</li>
<?php } ?>
If you can get the content of the article using ajax and put that content below that title of that article, for ex let say you have a php function in backend which you can call to get the content of article given the article id then you can make a GET ajax request to get the article content and put in the desired div. something like:
<script language="javascript">
$("#view_more").click(function(){
var dataString = "id="+article_ID;
$.ajax({
type: "GET",
url: 'http://myhost.com/articles/getArticleContent',
data: dataString,
success: function(response) {
$('div #description').html(response);
}
});
return false;
});
</script>
update:27-11-2012
you can try something like this, if that helps you understanding better. it may not be exactly what you want but I hope it will help you understanding how you can proceed.
<?php foreach ( $results['articles'] as $article ) { ?>
<li>
<h2>
<span class="pubDate"><?php echo date('j F Y', $article->publicationDate)?></span><br><?php echo htmlspecialchars( $article->title )?>
</h2>
<p class="summary" id="<?php echo $article->id?>">
<?php if ( $imagePath = $article->getImagePath( IMG_TYPE_THUMB ) ) { ?>
<a href=".?action=viewArticle&articleId=<?php echo $article->id?>">
<div class="floated_child0" style="background-repeat:none; background-image:url('<?php echo $imagePath?>');"></div></a>
<?php } ?>
<?php echo htmlspecialchars( $article->summary )?> (more)
</p>
</li>
<?php } ?>
<script language="javascript">
function viewFullArticle(article_ID){
var dataString = "id="+article_ID;
$.ajax({
type: "GET",
url: 'http://myhost.com/articles/getArticleContent',
data: dataString,
success: function(response) {
$('p #'+article_ID).html(response); //assuming response is everything you want to display within summary paragraph
}
});
return false;
};
</script>

Loading Content using Ajax with PHP Include

I have a PHP page which has a div, the div has a PHP includes which includes this file:
<?php
include('mySql.php');
include('Classes.php');
$targetPage = "blogOutput.php";
$noOfPosts = getNumberOfPosts();
$adjacents = 3;
?>
<link rel="stylesheet" type="text/css" href="Styles/Miniblog.css" />
<script src="Scripts/jQuery.js"></script>
<script type="text/javascript">
var page = 1;
$(".Button").click(onClick());
$(document).ready(onClick());
function onClick() {
alert('called');
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
}
</script>
<div class="PostTitle">
<h2>What's New!?</h2>
</div>
<div id="posts">
</div>
<a class="BlogButton" href="">Next</a>
I need the function "onclick" to be called without refreshing the page and resetting the "page" variable in javascript. So far, all I've been able to do is make it run the script once. I think that's wrong too, because it's not loading any content. Here's the page:
<?php
echo "I'm here!";
if (isset($_POST['offset'])) {
$offset = $_POST['offset'];
$posts = getPosts($offset);
}
?>
<div class="BlogPost">
<h3><?php echo $posts[0]->Title; ?></h3>
<p><?php echo $posts[0]->Body; ?></p>
<p class="Date"><?php echo $posts[0]->Date; ?></p>
</div>
<div id="divider"></div>
<div class="BlogPost">
<h3><?php echo $posts[1]->Title; ?></h3>
<p><?php echo $posts[1]->Body; ?></p>
<p class="Date"><?php echo $posts[1]->Date; ?></p>
</div>
So, to clarify: I'm not sure why my ajax call isn't working, and I don't know how to load just the div content and not refresh the entire page. Thanks!
You are not able to see content loaded by AJAX because the page is reloading as soon as you click the anchor. Disable the anchor event by using preventDefault() and this should fix it.
<script type="text/javascript">
var page = 1;
$(document).on('click','.BlogButton',function(e){
// stop page from reloading
e.preventDefault();
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
});
</script>
Don't call the function in the click method parameter. You have to put the reference to the handler function.
var handler = function onClick () {...}
$("whatever").click(handler);
Change your code to
var page = 1;
$(document).ready(function(){
$(".Button").click(onClick);
onClick();
};
Use this instead of your code
var page = 1;
$(document).on('click','.Button',function(){
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
});
Content dose not look too huge.Can't you just hide div (with content already present in it)& show it onclick.

Categories