ajax load content render in php return - php

I'm using ajax call api return json and render html append to page like below.
I have question is is possible after post parameter to api function then api function render in php then return rendered data to js, js just only append?
Because there is to much html structure if i write in js so difficult to read. Wondering most people how to do this?
$.ajax({
url: public_path+'/api_for_ajax/category/'+category_id+'/'+visible+'/'+rows_perpage+'/'+page,
type: 'POST',
processData: false,
contentType: false,
async: false
}).done(function(response) {
var response = JSON.parse(response);
$(data_article.article).each(function(i, each_data_article) {
var output = '<div class="article-list"><a href="'+public_path+'/article/'+each_data_article.id+'">
<div class="thumbnail"><img src="'+public_path+'/assets/thumbnails/'+each_data_article.thumbnail.thumbnail_id+'/'+each_data_article.thumbnail.file_name+'.'+each_data_article.thumbnail.file_format+'" alt=""></div>
<div class="subject">'+each_data_article.subject+'</div>
</a></div>';
// append
});
});
api
$data_select_category_id_page = $this->article_model->select_category_id_page($response_message, $category_id, $visible, $rows_perpage, $page);
$data = array();
$data['article'] = $data_select_category_id_page;
echo json_encode($data);
I tried in slim framework, it not work why??
api
$data_select_category_id_page = $this->article_model->select_category_id_page($response_message, $category_id, $visible, $rows_perpage, $page);
// 1
$app->render('frontstage/article/page_view.php', array(
'data_select_category_id_page' => $data_select_category_id_page,
)
);
// 2
return <<<HTML
<div><?php print_r($data_select_category_id_page);?></div>
HTML;
layout
<?php $column_count = 1; ?>
<div class="row">
<?php foreach ($data['article']['article'] as $i => $each_article) { ?>
<?php if ($i >= 4) { ?>
<div class="article-list">
<a href="<?php echo $uri['public']; ?>/article/<?php echo $each_article['id']; ?>">
<div class="thumbnail"><img src="<?php echo $uri['public']; ?>/assets/thumbnails/<?php echo $each_article['thumbnail']['thumbnail_id']?>/<?php echo $each_article['thumbnail']['file_name']?>.<?php echo $each_article['thumbnail']['file_format']?>" alt=""></div>
<div class="subject"><?php echo $each_article['subject'];?></div>
<div class="category-list-container">
<?php foreach ($each_article['category'] as $each_article_category) { ?>
<div class="category-list"><?php echo $each_article_category['subject']; ?></div>
<?php } ?>
<div class="clear"></div>
</div>
<?php
$old_date = $each_article['create_at'];
$old_date_timestamp = strtotime($old_date);
$new_date = date('d M Y', $old_date_timestamp);
?>
<div class="create-at"><?php echo $new_date;?></div>
</a>
</div>
<?php if (($column_count % 4) == 0) { ?>
<div class="clear"></div></div><div class="row">
<?php } ?>
<?php $column_count++;?>
<?php } ?>
<?php } ?>
<div class="clear"></div>

It is possible to have the server return the html rendered rather than JSON.
$.post( "ajax/test.php", function( data ) {
$( ".result" ).html( data );
});
Where test.php returns some kind of HTML data.
The test.php code will contain the logic to render the relevant html. Using the OP example as the logic, would look something like (untested) :
$public_path = '/sitepath/';
foreach($data_select_category_id_page as $article)
{
echo '<div class="aricle-list"><a href="' . $public_path . '/article/' . $article->id . '">
<div class="thumbnail"><img src="' . $public_path . '/assets/thumbnails/' . $article->thumbnail_id . '/' . $article->thumbnail->file_name . '.' . $article->thumbnail->file_format . '" alt=""></div>
<div class="subject">' . $article->subject . '</div>
</a></div>';
}
Or alternatively use a layout to render the html.
Beaware that the size of the rendered html being returned from the server is large than JSON.

Related

Wordpress use query as AJAX

I have a custom field selectbox where I chose which Posts I want to be displayed. Now I want the query, where I get the selected Posts and its custom fields, to somehow be used as an AJAX-call so that I can use the data-output to build a masonry-grid. Is that possible?
here is my data/query:
$posts = get_field('choose_artist');
if( $posts ): ?>
<?php foreach( $posts as $p ): ?>
<div class="artist">
<a href="<?php echo get_permalink( $p->ID ); ?>">
<div style="position: relative;">
<?php $image = get_field('artist_image', $p->ID); ?>
<div class="artist-image" style="background-image:url('<?php echo $image['url']; ?>')"></div>
<div class="overlay">
<div class="content">
<p><?php the_field('artist_name', $p->ID); ?></p>
</div>
</div>
</div>
</a>
</div>
<?php endforeach; ?>
So, my goal is something like:
$.ajax({
url: '/the query above',
success: function(data){
data is the query html
}})
Is that even possible?
ajax.php
$content = '';
if( $posts ) {
foreach( $posts as $p ) {
$image = get_field('artist_image', $p->ID);
$content .= '<div class="artist">';
$content .= '<a href="' . get_permalink( $p->ID ) . '">';
$content .= '<div style="position: relative;">';
$content .= '<div class="artist-image" style="background-image:url("' . $image['url'] . '")"></div>';
$content .= '<div class="overlay">';
$content .= '<div class="content">';
$content .= '<p>' . get_the_field('artist_name', $p->ID). '</p>';
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
$content .= '</a>';
$content .= '</div>';
}
}
echo $content;
main.js / .php (whereever you have the ajax call)
$.ajax({
url: '/ajax.php', //Path to the ajax.php script
success: function(data){
console.log(data);
}});
Check the documentation for how to catch errors, check for success etc. etc: http://api.jquery.com/jquery.ajax/
There are better ways to do the AJAX page, so refactor it and make it neater, but something similar to the above should work for you if I am understanding your needs, though you'll probably need to tweak it to get what you want.

Issues with undefined function that is in fact defined

I didn't build this PHP file, but I am trying to figure out why it is giving me errors. If the "Block layout mode" ACF variable is set to "Modal" then the block works, but gives me this error. "Undefined variable $vids on line 176". If I select the "Embed & Thumbnail" mode, then none of the block is displayed and I get this error. "Call to undefined function vc_embed_layout() on line 252". I can't pin down why this is happening, and I haven't been able to find any unclosed tags or anything in my php file. This is the file in question, and I've marked the lines that trigger errors.
<?php
global $theme_text_domain;
$block_class_identifier = 'blk__vidcol';
// default variables
$block_id = $top_class = $top_style = $inner_class = $inner_style = '';
// check for custom id
$block_id .= BLOCK::set_id( get_sub_field('content_block_id') );
// set block class, $i comes from FLEX class loop and represents the block order on a page
$top_class .= BLOCK::set_standard_classes( $i );
$top_class .= BLOCK::set_custom_classes( get_sub_field('content_block_classes') );
// check for top padding adjustment
$top_class .= BLOCK::set_padding_class( get_sub_field('block_padding_adjustment') );
$top_style .= BLOCK::set_padding_style( get_sub_field('block_padding_adjustment'), get_sub_field('custom_top_padding'), get_sub_field('custom_bottom_padding'));
// check for custom color theme
$top_style .= BLOCK::set_colors( get_sub_field('color_theme'), get_sub_field('text_color'), get_sub_field('custom_background_color') );
// check for width settings
$inner_class .= BLOCK::set_width_class( get_sub_field('content_width') );
$inner_style .= BLOCK::set_width_style( get_sub_field('content_width'), get_sub_field('custom_maximum_content_width') );
$block_assets = get_stylesheet_directory_uri() . '/inc/blocks/' . basename(__FILE__, '.php') . '/assets/';
/*
CUSTOM BLOCK SPECIFIC SETUP
*/
$layout = get_sub_field('block_layout_mode');
$top_class .= ' layout-' . $layout;
// title color
$h2_style = (get_sub_field('color_theme') == 'custom') ? ' color: ' . get_sub_field('custom_title_color') . ';' : '';
/**
* outputs code for the modal version of the video collection block
* #return html output
*/
if (!function_exists('vc_modal_layout')) {
function vc_modal_layout() {
global $block_class_identifier;
$cta_label = get_sub_field('cta_label');
$counter = 0;
$cta = array(
'style' => get_sub_field('cta_style'),
'button_color' => get_sub_field('button_color'),
'button_text_color' => get_sub_field('button_color')
);
$cta_class = BLOCK::get_cta_style( $cta, '.' . $block_class_identifier . ' .button');
?>
<?php // list section ?>
<?php if( have_rows('videos') ): ?>
<div class="vid-container">
<?php while ( have_rows('videos') ) : the_row(); ?>
<?php if ($counter == 0): ?>
<div class="vid-featured">
<div class="video-wrapper">
<iframe src="https://www.youtube.com/embed/<?php echo get_sub_field('youtube_embed_code'); ?>?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
<a class="vid_overlay" data-fancybox data-src="#<?php echo $block_class_identifier; ?>_vid_0" href="javascript:;"></a>
</div>
<!-- modal -->
<div id="<?php echo $block_class_identifier; ?>_vid_0" class="modal video-modal" style="display: none;">
<div class="modal-inner">
<h3><?php echo get_sub_field('video_title'); ?></h3>
<div class="video-wrapper">
<iframe src="https://www.youtube.com/embed/<?php echo get_sub_field('youtube_embed_code'); ?>?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
<div class="vid-list">
<?php else: ?>
<div class="vid-item">
<div class="item-btn">
<a class="button <?php echo $cta_class; ?>" data-fancybox data-src="#<?php echo $block_class_identifier; ?>_vid_<?php echo $counter; ?>" href="javascript:;"><?php echo $cta_label; ?></a>
</div>
<div class="item-title"><?php echo get_sub_field('video_title'); ?></div>
</div>
<!-- modal -->
<div id="<?php echo $block_class_identifier; ?>_vid_<?php echo $counter; ?>" class="modal video-modal" style="display: none;">
<div class="modal-inner">
<h3><?php echo get_sub_field('video_title'); ?></h3>
<div class="video-wrapper">
<iframe src="https://www.youtube.com/embed/<?php echo get_sub_field('youtube_embed_code'); ?>?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
<?php endif; ?>
<?php $counter++; ?>
<?php endwhile; ?>
</div>
</div>
<?php else: ?>
No videos defined.
<?php endif; ?>
<?
}
}
/**
* outputs code for the embed version of the video collection block
* #return html output
*/
if (!function_exists('vc_embed_layout')) {
function vc_embed_layout($vids, $i) {
?>
<?php if ( $vids ): ?> **this is line 176**
<div class="vid-container2">
<h2 class="vid-title"><?php echo $vids[0]['video_title']; ?></h2>
<div class="vid-container2-inner">
<div class="vid-embed">
<div class="video-wrapper">
<iframe src="https://www.youtube.com/embed/<?php echo $vids[0]['youtube_embed_code']; ?>?rel=0&showinfo=0" frameborder="0" allowfullscreen onload="this.style.visibility = 'visible';"></iframe>
</div>
</div>
<div class="vid-thumbnails">
<?php foreach ($vids as $key => $vid): ?>
<?php $wrap_class = ($key == 0) ? ' tn-hide' : ''; ?>
<div class="tn-wrapper <?php echo $wrap_class; ?>" data-embed="<?php echo $vid['youtube_embed_code']; ?>" data-title="<?php echo $vid['video_title']; ?>">
<img src="https://img.youtube.com/vi/<?php echo $vid['youtube_embed_code']; ?>/mqdefault.jpg" alt="">
</div>
<?php endforeach; ?>
</div>
</div>
<script>
var vid_swap = function() {
$('.block_<?php echo $i; ?> .vid-embed').css({opacity: 1});
$('.block_<?php echo $i; ?> .tn-wrapper').on('click', function(e) {
var $this = $(this);
var embed_id = $this.attr('data-embed');
var title = $this.attr('data-title');
console.log('embed = ' + embed_id);
$('.block_<?php echo $i; ?> .vid-title').animate({opacity: 0}, 100);
$('.block_<?php echo $i; ?> .vid-embed').animate({opacity: 0}, 1000, function() {
$('.block_<?php echo $i; ?> .vid-embed, .block_<?php echo $i; ?> .vid-title').css('visiblity','hidden');
$('.block_<?php echo $i; ?> .vid-title').html( title );
$('.block_<?php echo $i; ?> .vid-embed iframe').attr('src', 'https://www.youtube.com/embed/' + embed_id);
$('.block_<?php echo $i; ?> .tn-wrapper.tn-hide').removeClass('tn-hide');
$this.addClass('tn-hide');
$('.block_<?php echo $i; ?> .vid-title').css('visiblity','visible').delay(500).animate({opacity: 1}, 500);
$('.block_<?php echo $i; ?> .vid-embed').delay(500).animate({opacity: 1}, 1000);
});
});
}
jQuery(document).on('block_init', vid_swap);
</script>
</div>
<?php else: ?>
No videos defined.
<?php endif; ?>
<?php
}
}
?>
<section id="<?php echo $block_id; ?>" class="<?php echo $block_class_identifier; ?> <?php echo $top_class; ?>" style="<?php echo $top_style; ?>">
<div class="inner <?php echo $inner_class; ?>" style="<?php echo $inner_style; ?>">
<?php // title section ?>
<?php if (get_sub_field('title')): ?>
<h2 style="<?php echo $h2_style; ?>"><?php echo get_sub_field('title'); ?></h2>
<?php endif; ?>
<?php $vids = get_sub_field('videos'); ?>
<?php if ($layout == 'modal') vc_modal_layout($vids); ?>
<?php if ($layout == 'embed') vc_embed_layout($vids, $i); ?> **This is line 252**
</div>
</section>
You're not accepting any arguments in vc_modal_layout() function declaration.
if (!function_exists('vc_embed_layout')) {
function vc_embed_layout() {
needs to have parameters in order to accept arguments.
something like this is what you're looking for:
if (!function_exists('vc_embed_layout')) {
function vc_embed_layout($vids=[], $i=0) {
And it's the same idea with vc_modal_layout, the function needs to be able to accept the variables from outside it.
When we call a function, the function needs to be able to accept all arguments passed to it. And all variables we use need to be defined, if there's a risk of them being undefined or empty arrays, we can check them with if(!empty($var)) or if(isset($var))
An alternative to passing the variable to the function is to access it as a global. But it's generally better to pass the variable to the function because when we pass the variable to a function in PHP it works with a copy of the variable's value inside the function. When we do something like this:
$var = 10;
function doIt(){
global $var;
$var++;
}
doit();
echo $var;
we could overcomplicate things..
let's have a closer look here:
if ($layout == 'modal') vc_modal_layout($vids);
if ($layout == 'embed') vc_embed_layout($vids, $i); ?> **This is line 252**
function vc_modal_layout(){ ... }
// should be:
function vc_modal_layout($vids){ ... }
function vc_embed_layout($vids, $i)
// looks good.
Aside from that, nothing stands out as really unusual & I'd want to have a look at the actual site to tinker with this problem further.

WP Loop Geo + jQuery .hide() not working correctly

I have a WP loop where each post has a collection of 4 country based images (using ACF).
I only would like to output 1 image per country, however it is displaying all of 4 images per post.
<?php
$args = array( 'post_type' => 'quick_links', 'posts_per_page' => 3 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$image_au = get_field("au_image");
$image_nz = get_field("nz_image");
$image_us = get_field("us_image");
$image_gl = get_field("global_image"); //default image
?>
<script type="text/javascript">
var image_au = <?php echo json_encode($image_au['url']); ?>;
var image_nz = <?php echo json_encode($image_nz['url']); ?>;
var image_us = <?php echo json_encode($image_us['url']); ?>;
var image_gl = <?php echo json_encode($image_gl['url']); ?>;
jQuery.get("http://ipinfo.io", function (response) {
if (response.country === "AU"){
jQuery("#resultQLAU").show();
jQuery("#resultQLNZ").hide();
jQuery("#resultQLUS").hide();
jQuery("#resultQLGlobal").hide();
} else if(response.country === "NZ"){
jQuery("#resultQLNZ").show();
jQuery("#resultQLAU").hide();
jQuery("#resultQLUS").hide();
jQuery("#resultQLGlobal").hide();
} else if(response.country === "US"){
jQuery("#resultQLUS").show();
jQuery("#resultQLNZ").hide();
jQuery("#resultQLAU").hide();
jQuery("#resultQLGlobal").hide();
} else {
jQuery("#resultQLGlobal").show();
jQuery("#resultQLNZ").hide();
jQuery("#resultQLUS").hide();
jQuery("#resultQLAU").hide();
}
if(image_au === "" && image_nz === "" && image_us === "" && image_gl !== ""){
jQuery("#resultQLGlobal").show();
}
}, "jsonp");
</script>
<?php
echo '<div class="col-lg-4 col-sm-6" style="padding:2px">';
echo '<a href="' . get_field('page_url') . '" class="portfolio-box">';
?>
<div id="resultQLAU">
<img class="img-responsive" src="<?php echo $image_au['url']; ?>" alt="<?php echo $image_au['alt']; ?>" />
</div>
<div id="resultQLNZ">
<img class="img-responsive" src="<?php echo $image_nz['url']; ?>" alt="<?php echo $image_nz['alt']; ?>" />
</div>
<div id="resultQLUS">
<img class="img-responsive" src="<?php echo $image_us['url']; ?>" alt="<?php echo $image_us['alt']; ?>" />
</div>
<div id="resultQLGlobal">
<img class="img-responsive" src="<?php echo $image_gl['url']; ?>" alt="<?php echo $image_gl['alt']; ?>" />
</div>
<?php
echo '<div class="portfolio-box-caption">';
echo '<div class="portfolio-box-caption-content">';
echo '<div class="project-category text-faded">' . get_the_title() . '</div>';
echo '<div class="project-name">' . get_the_content() . '</div>';
echo '</div>';
echo '</div>';
echo '</a>';
echo '<h6 class="news-title text-center">' . get_the_title() . '<span style=""> <i class="fa fa-angle-double-right"></i></span></h6>';
echo '</div>';
endwhile;
?>
I originally had the code e.g <div id="resultQLAU" style="display:none"> and just had jQuery("#resultQLAU").show(); in script which outputed only the first
GEO image of the first post (so GEO was working correct for that 1 post)
Not sure what problem is?
Your help would be much appreciated. Thanks
You are using ID inside your loop so all the block will have the same ids which isn't good as id need to be unique. You may change this by adding a suffix/prefix depending the iteration and use classes instead.
1) add a new var the increment inside your loop like this :
$i = 0
while ( $loop->have_posts() ) : $loop->the_post();
$i++;
2) for each id append the content of $i, for example :
jQuery(".resultQLAU_<?php echo $i; ?>").show();
do this everywhere you have the id.

Load more data on page scroll Using php, Data source JSON

i developed a deal and coupon site and my data source is JSON. and my json file is big around 4MB. i want to show first 30 data and after scroll load next 30. so please tell me how can i do this work using JSON.
here is my code:
<?php $json = file_get_contents('offers.json');
$json_decode = json_decode($json,true);
foreach($json_decode as $data){
?>
<div class="ad-box">
<div class="ad-category"><?php echo $data['category'];?></div>
<div class="ad-image"><img class="lazy" data-src="<?php echo $data['imageUrl'];?>" src="" width="150" height="140" border="0" alt="lazy Image"/></div>
<div class="ad-title"><?php echo $data['title'] . " : " . $data['description'];?></div>
<div class="ad-url">Goto Offer</div>
</div>
<?php }
?>
your Json array is unknow but:
Main page:
<div id="loadbox">
<?php
$json = file_get_contents('offers.json');
$json_decode = json_decode($json, true);
for ($i = 0; $i < 29; $i++):
$data = $json_decode[$i];
?>
<div class="ad-box">
<div class="ad-category"><?php echo $data['category']; ?></div>
<div class="ad-image"><img class="lazy" data-src="<?php echo $data['imageUrl']; ?>" src="" width="150" height="140" border="0" alt="lazy Image"/></div>
<div class="ad-title"><?php echo $data['title'] . " : " . $data['description']; ?></div>
<div class="ad-url">Goto Offer</div>
</div>
<?php
endfor;
?>
</div>
<script type="text/javascript">
var last = 30;
function getData(lst) {
$.get("loader.php", {'last': lst}, function (data) {
$("#loadbox").append(data);
last += 30 ;
});
}
$(function () {
$(window).scroll(function () {
buffer = 40 // # of pixels from bottom of scroll to fire your function. Can be 0
if ($("html").prop('scrollHeight') - $("html").scrollTop() <= $("html").height() + buffer) {
getDate(last);
}
});
});
</script>
in the main page you load first 30 records and active ajax on scroll end.
when one loader for ajax request:
<?php
$json = file_get_contents('offers.json');
$json_decode = json_decode($json, true);
$start = (int) $_GET['last'] ;
for ($i = $start ; $i < ($start+30) ; $i++):
$data = $json_decode[$i];
?>
<div class="ad-box">
<div class="ad-category"><?php echo $data['category']; ?></div>
<div class="ad-image"><img class="lazy" data-src="<?php echo $data['imageUrl']; ?>" src="" width="150" height="140" border="0" alt="lazy Image"/></div>
<div class="ad-title"><?php echo $data['title'] . " : " . $data['description']; ?></div>
<div class="ad-url">Goto Offer</div>
</div>
<?php
endfor;
?>

Retrieving and appending HTML using PHP and Ajax

Hi there I am trying to append HTML to a list to create an infinite scroll effect, please do not reply by telling me to use a plugin.
I know from the inspector that onClick() is generating the HTML correctly via the PHP script it calls however the HTML generated is not being appended to the rest of the document.
Here's my code (JQuery has been imported):
HTML:
<body>
<div id='container'>
<?php include 'inc/header.php'; ?>
<?php include 'inc/nav.php'; ?>
<section class="grid-wrap">
<ul class="grid swipe-right custom-grid" id="grid">
<?php
$files = glob('img/gallery/*.{jpg,png,gif,JPG}', GLOB_BRACE);
$total = 9; //count($files);
for ($i = 0; $i < $total; ++$i) {
echo "<li><a href='" . $files[$i] . "' target='_blank'><img class='lazy' src='" . $files[$i] . "' alt= 'Image of Sheila' /><h3>View Full Image</h3></a></li>";
}
?>
</ul>
<div id='load-more'>VIEW MORE PHOTOS</div>
</section>
<?php include 'inc/footer.php'; ?>
</div>
<script>
$('#load-more').click(function(){
$.ajax({
url: 'inc/gallery/gallery2.php',
dataType: 'html',
sucess: function(php){$('.grid-wrap').append(php);}
});
});
</script>
</body>
gallery2.php :
<?php
$files = glob('../../img/gallery/*.{jpg,png,gif,JPG}', GLOB_BRACE);
$total = 9;
$id = 1;
echo '<ul class="grid swipe-right custom-grid" id="grid' . $id . '">';
for ($i = $total; $i < ($total + 9); ++$i) {
echo "<li>
<a href='" . $files[$i] . "' target='_blank'>
<img src='" . $files[$i] . "' alt= 'Image of Sheila' />
<h3>View Full Image</h3>
</a>
</li>";
}
$total+= 9;
echo '</ul>';
?>
Just a repost of my comment :x.
I think you mis-typed 'success' as 'sucess' for your ajax callback.
As Renald Lam said, you mis-typed success as sucess:
change this:
sucess: function(php){$('.grid-wrap').append(php);
to:
success: function(php){$('.grid-wrap').append(php);
U missing s in success function and try
$('#load-more').click(function(){
$.ajax({
url: 'inc/gallery/gallery2.php',
dataType : 'html',
success: function(php){
$('.grid-wrap ul').append(php);
}
});
});

Categories