Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Ajax Load template part WordPress

  • SOLVED

I'm having issues trying to load a template part via Ajax. The template part controls a lightbox modal and the data for the lightbox is being pulled from advanced custom fields. The Ajax load is working, but it's not outputting any of the ACF data.

Here is the functions.php code

add_action( 'wp_ajax_nopriv_ajax_lightBox', 'my_ajax_lightBox' );
add_action( 'wp_ajax_ajax_lightBox', 'my_ajax_lightBox' );
function my_ajax_lightBox() {
get_template_part('templates/lightbox', 'widget');
die();
}

Here is the js code for the ajax load
$(document).on( 'click', '.lightOpen', function( event ) {
event.preventDefault();
$.ajax({
url: ajaxurl,
type: 'post',
data: {
action: 'ajax_lightBox',
},
success: function( result ) {
$"#page-wrap").append(result);
}
})
});


Here is the code for the template part
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php $images = get_field('light_gallery');
if( $images ): ?>
<header class="lbHead">
<div class="slideCount"><span class="slide-current-slide">1</span><span class="slide-total-slides">2</span></div>
<span class="close-btn"> x </span>
<a href="#" class="downloadImg" target="_blank"></a>
</header>
<section class="slider">
<div class="preloader">
<img src="preloader.gif">
</div> <div class="flexslider carousel">
<ul class="slides">
<?php foreach( $images as $image ): ?>
<li class="lazy" style="background-image: url(<?php echo $image['url']; ?>);">
<p class="flex-caption"><?php echo $image['caption']; ?></p>
</li>

<?php endforeach; ?>
</ul>

<?php endif; ?>
</div>

<div id="carousel">
<ul class="slides">
<?php foreach( $images as $image ): ?>
<li>
<img src="<?php echo $image['sizes']['thumbnail']; ?>" />
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="customSliderNav">
</div>
<?php endwhile; endif; ?>
</section>

Answers (4)

2017-09-01

Farid answers:

Looks like you haven't defined "ajaxurl" variable anywhere. If not then please define it.

If you have defined then can you let me know where you have defined it?


Farid comments:

I have checked it and found it working. What is missing only 'ajaxurl' variable is undefined.

Make sure you have your form action is set something like this:

<form class="contact-form" method="post" action="<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>">

After that define your 'ajaxurl' like this:

$(document).on( 'click', '.lightOpen', function( event ) {

var ajaxurl = $('#form-id').attr('href'); // it will point to the ajax url

event.preventDefault();
$.ajax({
url: ajaxurl,
type: 'post',
data: {
action: 'ajax_lightBox',
},
success: function( result ) {
$"#page-wrap").append(result);
}
})
});


ktp12345 comments:

Sorry I left that part out. The ajax url is defined
ajaxurl = 'http://www.sitename.com/wp-admin/admin-ajax.php';


Farid comments:

Okay then you would need to set the posts query properly in the template part that you are fetching in your ajax request.

Please implement this:

$recent_posts_args = array(
'post_type' => 'post',
'posts_per_page' => 3,
'ignore_sticky_posts' => 1,
);

// The Query
$recent_posts_query = new WP_Query($recent_posts_args);

// The Loop
if ($recent_posts_query->have_posts()) {
while ( $recent_posts_query->have_posts() ) {
$recent_posts_query->the_post();

// post query code here

}
}


Farid comments:

Here is your complete template part file code:


<?php

$recent_posts_args = array(
'post_type' => 'post',
'posts_per_page' => 3,
'ignore_sticky_posts' => 1,
);

// The Query
$recent_posts_query = new WP_Query($recent_posts_args);

if ($recent_posts_query->have_posts()) : while ($recent_posts_query->have_posts()) : $recent_posts_query->the_post(); ?>
<?php $images = get_field('light_gallery', get_the_ID());


if( $images ): ?>
<header class="lbHead">
<div class="slideCount"><span class="slide-current-slide">1</span><span class="slide-total-slides">2</span></div>
<span class="close-btn"> x </span>
<a href="#" class="downloadImg" target="_blank"></a>
</header>
<section class="slider">
<div class="preloader">
<img src="preloader.gif">
</div> <div class="flexslider carousel">
<ul class="slides">
<?php foreach( $images as $image ): ?>
<li class="lazy" style="background-image: url(<?php echo $image['url']; ?>);">
<p class="flex-caption"><?php echo $image['caption']; ?></p>
</li>

<?php endforeach; ?>
</ul>

<?php endif; ?>
</div>

<div id="carousel">
<ul class="slides">
<?php foreach( $images as $image ): ?>
<li>
<img src="<?php echo $image['sizes']['thumbnail']; ?>" />
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="customSliderNav">
</div>
<?php endwhile; endif; ?>
</section>


Farid comments:

I have updated only this part: http://jmp.sh/JVEExB6

I also passed the post id to the 'get_field' function.

This is the doc of get_field function if you need: https://www.advancedcustomfields.com/resources/get_field/


ktp12345 comments:

For the template part It's ignoring everything from between the php tags and only outputting </section> which is outside the tags. And If I remove the php tags it outputs everything as html.


Farid comments:

It seems like there is a PHP error in the template when you load it via ajax.

Did you try to load that template directly in a page? Does it work fine there?


ktp12345 comments:

Yes, the template works fine. It's what I've been using to load all the lightboxes. The only reason I'm trying to update this with an ajax load is to because I didn't want to load the image galleries until someone clicked it.


Farid comments:

I do understand I have done it several times as I am a themeforest author and have been developing WordPress themes since a long time.

Can you provide me more details about your site through my profile contact form here: https://themeforest.net/user/pearlthemes

So that I can look into it and fix it right away.

Thank you!


Farid comments:

I have improved the code and updated on your site. It is returning the images html of the template for the current page exactly as you needed :)

Let me know if you still would need any help from my side. Otherwise done the job :)

Thank You!


ktp12345 comments:

It worked thank you!


Farid comments:

Cheers! Have a great time.

2017-09-01

Arnav Joy answers:

well your template is missing post id that's why it is unable to pick the fields.


Arnav Joy comments:

please try this
<?php
add_action( 'wp_ajax_nopriv_ajax_lightBox', 'my_ajax_lightBox' );
add_action( 'wp_ajax_ajax_lightBox', 'my_ajax_lightBox' );
function my_ajax_lightBox() {
query_post('p='.$_POST['post_id'].'&post_type=post');
get_template_part('templates/lightbox', 'widget');
die();
}
?>
<script>
$(document).on( 'click', '.lightOpen', function( event ) {
event.preventDefault();
$.ajax({
url: ajaxurl,
type: 'post',
'post_id' => post_id
data: {
action: 'ajax_lightBox',
},
success: function( result ) {
$"#page-wrap").append(result);
}
})
});

</script>

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php $images = get_field('light_gallery');
if( $images ): ?>
<header class="lbHead">
<div class="slideCount"><span class="slide-current-slide">1</span><span class="slide-total-slides">2</span></div>
<span class="close-btn"> x </span>
<a href="#" class="downloadImg" target="_blank"></a>
</header>
<section class="slider">
<div class="preloader">
<img src="preloader.gif">
</div> <div class="flexslider carousel">
<ul class="slides">
<?php foreach( $images as $image ): ?>
<li class="lazy" style="background-image: url(<?php echo $image['url']; ?>);">
<p class="flex-caption"><?php echo $image['caption']; ?></p>
</li>

<?php endforeach; ?>
</ul>

<?php endif; ?>
</div>

<div id="carousel">
<ul class="slides">
<?php foreach( $images as $image ): ?>
<li>
<img src="<?php echo $image['sizes']['thumbnail']; ?>" />
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="customSliderNav">
</div>
<?php endwhile; endif; ?>
</section>


Arnav Joy comments:

in this code I have done two things

1. passed post_id to js function

'post_id' => post_id

2. added query_posts('p='.$_POST['post_id'].'&post_type=post');

please correct name of the function to query_posts I have missed 's' above.


ktp12345 comments:

I'm getting a JS error. missing : after property id. I'm guessing this line needs to be formatted a little different 'post_id' => post_id


Arnav Joy comments:

please check this


please try this
<?php
add_action( 'wp_ajax_nopriv_ajax_lightBox', 'my_ajax_lightBox' );
add_action( 'wp_ajax_ajax_lightBox', 'my_ajax_lightBox' );
function my_ajax_lightBox() {
query_posts('p='.$_POST['post_id'].'&post_type=post');
get_template_part('templates/lightbox', 'widget');
die();
}
?>
<script>
$(document).on( 'click', '.lightOpen', function( event ) {
event.preventDefault();
$.ajax({
url: ajaxurl,
type: 'post',

data: {
action: 'ajax_lightBox',
'post_id' => post_id
},
success: function( result ) {
$"#page-wrap").append(result);
}
})
});

</script>

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php $images = get_field('light_gallery');
if( $images ): ?>
<header class="lbHead">
<div class="slideCount"><span class="slide-current-slide">1</span><span class="slide-total-slides">2</span></div>
<span class="close-btn"> x </span>
<a href="#" class="downloadImg" target="_blank"></a>
</header>
<section class="slider">
<div class="preloader">
<img src="preloader.gif">
</div> <div class="flexslider carousel">
<ul class="slides">
<?php foreach( $images as $image ): ?>
<li class="lazy" style="background-image: url(<?php echo $image['url']; ?>);">
<p class="flex-caption"><?php echo $image['caption']; ?></p>
</li>

<?php endforeach; ?>
</ul>

<?php endif; ?>
</div>

<div id="carousel">
<ul class="slides">
<?php foreach( $images as $image ): ?>
<li>
<img src="<?php echo $image['sizes']['thumbnail']; ?>" />
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="customSliderNav">
</div>
<?php endwhile; endif; ?>
</section>


Arnav Joy comments:

please note .. in my above code you have to do following two things:-

1. query_posts('p='.$_POST['post_id'].'&post_type=post');

post_type should be correct

2. 'post_id' => post_id

post_id should be passed when on click event is called

2017-09-01

Rempty answers:

Hello
You canĀ“t use the template part without a query, the ajax call are loaded like a new page
so you need to send the POST ID via ajax and make a query

First add a attribute to the link with class lightOpen
maybe like this
<a class="lightOpen" data-post_id="<?php get_the_ID()?>">Open Lightbox</a>
I added the attr data-post_id and assigned the ID of the post

After that you need to modify the javascript ajax to send the post_id
[code]
$(document).on( 'click', '.lightOpen', function( event ) {
event.preventDefault();
$postid=jQuery(this).attr('data-post_id');
$.ajax({
url: ajaxurl,
type: 'post',
data: {
action: 'ajax_lightBox',
'post_id':$postid
},
success: function( result ) {
$"#page-wrap").append(result);
}
})
});
[/code]

Now in the ajax function you can't include the template, need to copy the template part to the function and make aquery first to load the data from the post

[code]
function my_ajax_lightBox() {
$ajaxq=new WP_Query(
array(
'p'=>$_POST['post_id'],
'post_type'=>'post'
)
);
ob_start();
?>
<?php if ($ajaxq->have_posts()) : while ($ajaxq->have_posts()) : $ajaxq->the_post(); ?>
<?php $images = get_field('light_gallery');
if( $images ): ?>
<header class="lbHead">
<div class="slideCount"><span class="slide-current-slide">1</span><span class="slide-total-slides">2</span></div>
<span class="close-btn"> x </span>
<a href="#" class="downloadImg" target="_blank"></a>
</header>
<section class="slider">
<div class="preloader">
<img src="preloader.gif">
</div> <div class="flexslider carousel">
<ul class="slides">
<?php foreach( $images as $image ): ?>
<li class="lazy" style="background-image: url(<?php echo $image['url']; ?>);">
<p class="flex-caption"><?php echo $image['caption']; ?></p>
</li>

<?php endforeach; ?>
</ul>

<?php endif; ?>
</div>

<div id="carousel">
<ul class="slides">
<?php foreach( $images as $image ): ?>
<li>
<img src="<?php echo $image['sizes']['thumbnail']; ?>" />
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="customSliderNav">
</div>
<?php endwhile; endif; ?>
</section>

<?php
$contenido = ob_get_contents();
ob_end_clean();
echo $contenido;
die();
}
[/code]

in the WP_Query dont forget check if the post_type is the correct one

2017-09-01

Pau answers:

Try changing loop code in your template file with:

<?php
global $wp_query;
if( $wp_query->have_posts() ) : while( $wp_query->have_posts() ) : $wp_query->the_post();
?>

or to be specific:
<?php
$query = new WP_Query( array(
'showposts' => 'number of post to display',
'post_type' => 'post type here'
) );
if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post();
?>

then at the very bottom part, add:
<?php wp_reset_postdata() ?>