Load more data from database with Codeigniter and Ajax - php

I need help with a button for loading more data from the database. I've found examples, but too bad ones. Here is what I have so far:
The Ajax:
$('#revendas_conteudo .btn_carregar_mais').on('click', function(e) {
$.ajax({
url: '/auto/carros/load_more',
data: {
offset: $('#offset').val(),
limit: $('#limit').val()
},
success: function(data) {
$('#revendas_conteudo .lista_estoque').append(data);
}
});
});
My Controller method calling the Model load_more:
public function load_more()
{
$offset = $this->input->get('offset');
$limit = $this->input->get('limit');
$data['res'] = $this->Pesquisas_model->load_more($offset, $limit);
$data['offset'] = $offset + 1;
$data['limit'] = $limit + 1;
echo json_encode($data);
}
Pesquisas_model::load_more():
public function load_more($offset, $limit)
{
$this->db
->select(
'usuario.nome_razao_social AS nome_anunciante,' .
'modelo.modelo AS modelo,' .
'marca.marca AS marca,' .
'ano_modelo.ano AS ano,' .
'ano_modelo.valor AS valor,' .
'ano_modelo.combustivel AS combustivel,' .
'cambio.descricao_cambio AS descricao_cambio,' .
'estado.uf AS uf,' .
'cidade.nome_cidade AS nome_cidade,' .
'carro.*'
)
->join('usuario', 'usuario.id = carro.id_usuario')
->join('ano_modelo', 'ano_modelo.id = carro.id_ano_modelo')
->join('modelo', 'modelo.id = ano_modelo.id_modelo')
->join('marca', 'marca.id_marca = modelo.id_marca')
->join('cambio', 'cambio.id = carro.id_cambio')
->join('estado', 'estado.id = carro.id_estado')
->join('cidade', 'cidade.id = carro.id_cidade')
->order_by('marca.marca', 'ASC')
->limit($offset, $limit);
$query = $this->db->get($this->table);
if ($query) {
$data = array();
foreach ($query->result_array() as $row) {
$data[] = $row;
}
$query->free_result();
return $data;
}
}
The HTML:
<div class="lista_estoque">
<?php foreach ($pesquisas as $p) { ?>
<div class="item_estoque">
<div class="avatar">
<img src="/uploads/carros/destaque/<?php echo $p['imagem_destaque']; ?>"/>
</div>
<div class="texto_anuncio">
<h4><?php echo $p['modelo']; ?></h4>
<div class="detalhes">
<span><?php echo $p['marca'] . ' | ' . $p['combustivel'] . ' | ' . $p['cor']; ?></span>
<span><?php echo $p['ano']; ?></span>
<span><?php echo number_format($p['kilometragem'], 2) . 'km'; ?></span>
</div>
<span class="anunciante"><?php echo $p['nome_anunciante']; ?></span>
</div>
<div class="texto_anuncio_right">
<span class="preco"><?php echo 'R$ ' . $p['preco']; ?></span>
Veja Mais
</div>
</div>
<?php } ?>
<div class="carregar_mais">
<input type="hidden" name="limit" id="limit" value="1"/>
<input type="hidden" name="offset" id="offset" value="1"/>
<button class="btn btn_carregar_mais" data-val="0">Mostrar mais resultados</button>
</div>
So far what happens is a JSON code is appended to the end of the div. How do I make this data be converted into HTML and its classes?

converting a json text to a java
var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
var obj = JSON.parse(text);
use the js object
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>

create a view called load_more.php in your view folder ..
Your Controller will be like this
public function load_more()
{
$offset = $this->input->get('offset');
$limit = $this->input->get('limit');
$data['pesquisas '] = $this->Pesquisas_model->load_more($offset, $limit);
$data['offset'] = $offset + 1;
$data['limit'] = $limit + 1;
data['load_more']=$this->load->view('load_more',$data);
}
And in your view load_more.php
<?php foreach ($pesquisas as $p) { ?>
<div class="item_estoque">
<div class="avatar">
<img src="/uploads/carros/destaque/<?php echo $p['imagem_destaque']; ?>"/>
</div>
<div class="texto_anuncio">
<h4><?php echo $p['modelo']; ?></h4>
<div class="detalhes">
<span><?php echo $p['marca'] . ' | ' . $p['combustivel'] . ' | ' . $p['cor']; ?></span>
<span><?php echo $p['ano']; ?></span>
<span><?php echo number_format($p['kilometragem'], 2) . 'km'; ?></span>
</div>
<span class="anunciante"><?php echo $p['nome_anunciante']; ?></span>
</div>
<div class="texto_anuncio_right">
<span class="preco"><?php echo 'R$ ' . $p['preco']; ?></span>
Veja Mais
</div>
</div>
<?php } ?>
Jquery
success: function(data) {
var res= JSON.parse(data);
$('#revendas_conteudo .lista_estoque').append(data.load_more);
$('.carregar_mais input[name=limit]').val(data.limit);
$('.carregar_mais input[name=offset]').val(data.offset);
});

In the following function in controller, you need to add a view where you echo the content properly with html markups and classes as defined by you.
Currently, you are echoing the json_encode format. That's why it is printing as it is.
public function load_more()
{
$offset = $this->input->get('offset');
$limit = $this->input->get('limit');
$data['res'] = $this->Pesquisas_model->load_more($offset, $limit);
$data['offset'] = $offset + 1;
$data['limit'] = $limit + 1;
//echo json_encode($data);
$this->load->view('load-more',$data['res']);
}

Most of the answers here have led me to the solution. Sadly I can't tag all of them as the correct answer, so allow me to post what I did:
First, this is the full Ajax. I could not make it work with an external file as suggested, so it is like this:
$('#revendas_conteudo .btn_carregar_mais').on('click', function(e) {
$.ajax({
url: '/auto/carros/load_more',
data: {
'offset': $('#offset').val(),
'limit': $('#limit').val()
},
success: function(data) {
var obj = JSON.parse(data);
var i = 0;
var max = obj.total === obj.offset;
$('#limit').val(obj.limit);
$('#offset').val(obj.offset);
$.each(obj, function(k, v) {
$('#revendas_conteudo .load_more').append(
'<div class="item_estoque">' +
'<div class="avatar">' +
'<img src="/uploads/carros/destaque/' + obj.res[i].imagem_destaque + '"/>' +
'</div>' +
'<div class="texto_anuncio">' +
'<h4>' + obj.res[i].modelo + '</h4>' +
'<div class="detalhes">' +
'<span>' + obj.res[i].marca + ' | ' + obj.res[i].combustivel + ' | ' + obj.res[i].cor + '</span>' +
'<span>' + obj.res[i].ano + '</span>' +
'<span>' + obj.res[i].kilometragem + ' km</span>' +
'</div>' +
'<span class="anunciante">' + obj.res[i].nome_anunciante + '</span>' +
'</div>' +
'<div class="texto_anuncio_right">' +
'<span class="preco"> R$ ' + obj.res[i].preco + '</span>' +
'Veja Mais' +
'</div>' +
'</div>'
).show('slow');
i++;
if (max) {
$('#revendas_conteudo .btn_carregar_mais').css({backgroundColor: '#999'}).html('Sem mais resultados').attr('disabled', true);
}
});
}
});
});
In here I append every new result to the div.load_more, and if the total is identical to the current offset, it means it has already shown all the values, making the button unavailable for clicking.
Here, the controller method:
public function load_more()
{
$offset = $this->input->get('offset');
$limit = $this->input->get('limit');
$data['res'] = $this->Pesquisas_model->load_more($offset, $limit);
$data['total'] = $this->Pesquisas_model->count_all();
if ($data['res']) {
$data['offset'] = $offset + 2;
$data['limit'] = $limit;
echo json_encode($data);
}
}

Related

Dropdown nested categories with unlimited subcategories -> Ajax / Laravel

Im trying to create Nested Dropdown categories using the following code:
My DB-> Table product_categories with fields:
-id
-categoryName
-parentId-level
-is_active
My Product Entity to retrieve categories:
public function getAjaxGetCategoriesDropdown() {
$categories = DB::table('product_categories')
->where('is_active', 1)
->orderBy('path', 'asc')
->select('categoryName','level','id','parentId')
->get();
$first = array();
$children = array();
foreach ($categories as $cat) {
if ($cat->level == 2) {
$first[$cat->id] = $cat;
} else if ($cat->parentId) {
$children[$cat->parentId][] = $cat;
}
}
return array('first' => $first, 'children' => $children);
}
Controller:
public function create()
{
$cats = $this->product->getAjaxGetCategoriesDropdown();
return View('products/create_product')->with(compact('products','cats'));
}
In View: (create.blade.php)
<div class="section">
<label class="field select">
<select id="first_cat" class="required-entry validate-select" onchange="showCat(this, 2)">
<option value=""> Select a Category </option>
<?php foreach ($tree['first'] as $cat): ?>
<option value="<?php echo $cat->id ?>"><?php echo $cat->categoryName ?></option>
<?php endforeach ?>
</select>
<i class="arrow double"></i>
</label>
<div id="sub_cat"></div>
</div>
My Script:
<script type="text/javascript">
var children = $H(<?php echo json_encode($tree['children']) ?>);
function showCat(obj, level) {
var catId = obj.value;
level += 1;
if ($('cat_container_' + level)) {
$('cat_container_' + level).remove();
}
if (children.get(catId)) {
var options = children.get(catId);
var html = '<select id="cat_' + catId + '" onchange="showCat(this, ' + level + ')">' + '<option value="">Select a SubCategory</option>';
for (var i = 0; i < options.length; i++) {
html += '<option value="' + options[i].entity_id + '">' + options[i].name + '</option>';
}
html += '</select>' + '<i class="arrow double"></i>';
html = '<label class="field select ' + 'cat_container_' + level + '">' + html + '</label>';
$('sub_cat').insert(html);
}
}
</script>
The current error that the Log displays says:
Undefined Variable Tree in create.blade.php
.. code <?php foreach ($tree['first'] as $cat): ?>
I've been using this code with success on a Magento app, but now porting the same approach to Laravel is not showing results. Any help appreciated.
Change
foreach($tree ...
To
foreach($cats ...
In your view file.

How to make custom search & filter page in wordpress?

I want to make custom search page where I can filter results as shown in the screenshot below:
Currently my problem is that all the items of the list are coming in a single category while I want a grouped view according to different categories e.g. "Device Features", "Mobile Phone Operating System", etc. So far I've written below piece of PHP code:
<?php
$listCategories = get_categories();
if(isset($listCategories) && !empty($listCategories)){
?>
<div class="list-section">
<h3 class="list-heading">Topics</h3>
<ul id="post-grid">
<?php
foreach($listCategories as $categories){
$total_post = get_posts(array('post_type'=>'post', 'category'=>$categories->term_id, 'posts_per_page'=>'-1'));
$total_post = count($total_post);
?>
<li>
<div class="checkbox">
<input type="checkbox" id="cat<?php echo $categories->term_id; ?>" data-tax="category" data-name="<?php echo $categories->name; ?>" class="category_check" value="<?php echo $categories->term_id; ?>">
<label class="css-label" for="cat<?php echo $categories->term_id; ?>">
<span class="filter-name"><?php echo $categories->name; ?></span>
<span class="filter-count"><?php echo $total_post; ?></span>
<i class="icon fa fa-check"></i>
</label>
</div>
</li>
<?php } ?>
</ul>
</div>
<?php } ?>
I've created my own custom plugin for searching and filtering the search result.
1. Plugin file (index.php)
<?php
/*
Plugin Name: Search and Filter
Plugin URI: http://wordpress.org
Description: Search and Filter
Author: Naveen
Version: 1.0
*/
class SearchAndFilter{
public function __construct()
{
add_action('wp_enqueue_scripts', array($this, 'AddScript'));
add_action('wp_ajax_affordance_search_data' , array($this, 'AffordanceSearchData'));
add_action('wp_ajax_noprev_affordance_search_data' , array($this, 'AffordanceSearchData'));
add_action('wp_ajax_affordance_search_page_data' , array($this, 'AffordanceSearchPageData'));
add_action('wp_ajax_noprev_affordance_search_page_data' , array($this, 'AffordanceSearchPageData'));
add_shortcode('Search', array($this, 'CreateShortcode'));
}
public function AddScript()
{
wp_enqueue_script('saf-app', plugin_dir_url(__FILE__) . '/js/app.js', array('jquery'));
wp_localize_script('saf-app', 'my_ajax_object', array('ajaxurl' => admin_url('admin-ajax.php')));
}
function CreateShortcode($atts)
{
ob_start();
$keyword = $_REQUEST['s'];
?>
<form action="<?php echo home_url('/'); ?>" method="get">
<input type="text" name="s" id="search_keyword" value="<?php echo $keyword; ?>" class="form-control search-input" placeholder="Search..." />
</form>
<div class="search-suggestion"></div>
<?php
$output = ob_get_clean();
return $output;
}
// search autocomplete
function AffordanceSearchData()
{
$args = array('post_type'=>array('post'),'status'=>'publish');
$output = '';
$output = '<ul class="grid effect-3" id="grid">';
if(isset($_POST['keyword']) && !empty($_POST['keyword']))
{
$args['s'] = $_POST['keyword'];
}
$wpPosts = new WP_Query($args);
if($wpPosts->have_posts()) :
while($wpPosts->have_posts()) :
$wpPosts->the_post();
$output .= '<li class="col-md-4 col-sm-6 col-xs-12">'.get_the_title().'</li>';
endwhile;
endif;
$output .= '<li>See All Result of '.$_POST['keyword'].' </li>';
$output .= '</ul>';
wp_reset_query();
echo $output; die;
}
// filters search data
function AffordanceSearchPageData()
{
$args = array('post_type'=>'post','status'=>'publish');
$output = '';
$output .= '<ul class="grid effect-3" id="grid">';
if(isset($_POST['keyword']) && !empty($_POST['keyword']))
{
$args['s'] = $_POST['keyword'];
}
if(isset($_POST['page_number']) && !empty($_POST['page_number']) && $_POST['page_number'] != 1){
$args['paged'] = $_POST['page_number'];
}
if(isset($_POST['categories']) && !empty($_POST['categories'])){
$args['cat'] = $_POST['categories'];
}
$wpPosts = new WP_Query($args);
if($wpPosts->have_posts()) :
while($wpPosts->have_posts()) :
$wpPosts->the_post();
$output .= '<li class="col-md-4 col-sm-6 col-xs-12">
<h3 class="resources-content-heading">'.get_the_title().'</h3>
<p class="resources-content-description">'.get_the_excerpt().'</p>
<div class="resources-action-area">
Read More <i class="fa fa-angle-right" aria-hidden="true"></i>
</div>
</li>';
endwhile;
else :
$output .= "No records";
endif;
wp_reset_query();
$output .= the_posts_pagination();
$output .= '</main>';
echo $output; die;
}
}
new SearchAndFilter();
2. Js File (app.js)
jQuery(document).ready(function ($) {
// on searching keyword
$('#search_keyword').keyup(function () {
var inputvalue = $(this).val();
if (inputvalue != '') {
GetSuggestion(inputvalue);
}
});
// on pagination click
$('.ajaxclick').on('click', "a", function () {
var page_number = $(this).attr('data-page-num');
//console.log(page_number);
var current_page = $('.ajaxclick .current').attr('data-page-num');
var keyword = $('#search_keyword').val();
GetSearchData(keyword, page_number);
});
// on category select
$('.category_check').on('click', function () {
var page_number = 1;
var keyword = $('#search_keyword').val();
var blogWrapper = $('.blogWrapper');
var catTagHTML = '<ul>';
blogWrapper.find('input.category_check:checked').each(function () {
catTagHTML += '<li><a class="exclude_cat" href="javascript:void(0)" data-cat-id="' + $(this).attr('value') + '">' + $(this).attr('data-name') + '</a></li>';
});
$('#selected-category-tags').html(catTagHTML);
GetSearchData(keyword, page_number);
});
// on tag click
$('#selected-category-tags').on('click', "a.exclude_cat", function () {
var page_number = 1;
var keyword = $('#search_keyword').val();
var catID = $(this).attr('data-cat-id');
$('#cat' + catID).attr('checked', false);
$(this).closest('li').remove();
GetSearchData(keyword, page_number);
});
function GetSuggestion(keyword) {
var formData = {
'action': 'affordance_search_data',
'keyword': keyword
}
$.ajax({
type: "post",
url: my_ajax_object.ajaxurl,
data: formData,
success: function (data) {
setTimeout(function () {
$('.search-suggestion').html(data);
}, 1000);
}
});
}
function GetSearchData(keyword, page_number) {
if (page_number == '') {
page_number = 1;
}
var blogWrapper = $('.blogWrapper');
var categories = [];
blogWrapper.find('input.category_check:checked').each(function () {
categories.push($(this).attr('value'));
});
var formData = {
'action': 'affordance_search_page_data',
'page_number': page_number,
'keyword': keyword,
'categories': categories,
}
$.ajax({
type: "post",
url: my_ajax_object.ajaxurl,
data: formData,
success: function (data) {
setTimeout(function () {
$('.site-main').html(data);
}, 1000);
}
});
}
});
Here I'm using ajax to achieve this functionality.

jQuery Drag & Drop not working when loading images from PHP file with jquery .load() function

i have a tabbed box with two tabs, one that contains "characters" and one that contains "weapons". if i load the images into their respective containers using PHP directly inside my HTML, the images drag fine, but i can't get both containers to load their contents; it only loads the contents retrieved by the first instance of PHP code. when i put the respective codes into separate php files and use .load(), though, the contents load fine, but are no longer draggable.
HTML for the tab box:
<div class="tabBox">
<ul class="tabs">
<li class="card-gallery" active>Cards</li>
<li class="weapon-gallery">Weapons</li>
</ul>
<div class="tabContainer">
<div id="card-gallery" class="tabContent">
</div>
<div id="weapon-gallery" class="tabContent">
</div>
</div>
</div>
jQuery script to make the tabs work:
$(".tabContent").hide();
$('#card-gallery').load('cardgallery.php');
$('#weapon-gallery').load('weaponsgallery.php');
$(".tabContent").eq(0).show();
$(".tabs li").on('click', function(event) {
var showTab = $(this).attr('class')
if (showTab == 'card-gallery') {
$('.tabContent').hide();
$('#card-gallery').show();
$(this).siblings().removeAttr('active');
$(this).attr('active',true);
} else if (showTab == 'weapon-gallery') {
$('.tabContent').hide();
$('#weapon-gallery').show();
$(this).siblings().removeAttr('active');
$(this).attr('active',true);
}
});
jQuery draggable (currently only for "characters" tab):
$("#card-gallery .draggable").draggable({
containment: "document",
helper: "clone",
appendTo: 'body',
scroll: false
});
PHP for loading images:
<?php
$db = new mysqli("localhost", "____", "____", "builder")
or die('Error connecting to MySQL server.');
$result = mysqli_query($db, 'SELECT id, i_card_type, name, i_character,
i_rarity, i_weapon, image, special_icon
FROM card_data
LIMIT 1,200');
$i=0;
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
if (strpos($row[2], '(') !== false) {
$cardtitle = preg_split("/(【|】|\(|\))/u", $row[2]);
} else {
$cardtitle = preg_split("/(【|】)/u", $row[2]);
}
if ($i++ % 3 == 0) echo '<div class="row">';
echo '<div class="card-box">';
echo '<div id="' . $row[0] . '" class="draggable"
data-card-type="' . $row[1] . '"data-cid="' . $row[3] . '"
data-wid="' . $row[5] . '" data-rarity="' . $row[4] . '">';
echo '<div class="icon-box">';
echo '<div class="invalid-card-text"></div>';
echo '<div class="icon-image">';
echo '<img src="' . $row[6] . '" />';
if ($row[7] != 'NULL') {
echo '<img class="sicon" src="' . $row[7] . '" />';
}
echo '<img class="wicon" src="weapons/img/type/' . $row[5] . '.png" />';
echo '</div>';
echo '</div>';
echo '</div>';
echo '<p class="card-name">';
echo '【<b>' . $cardtitle[1] . '</b>】';
echo '<br />';
echo $cardtitle[2];
if (strpos($row[2], '(') !== false) {
echo '<br />';
echo '<p class="small">( ' . $cardtitle[3] . ' )</p>';
}
echo '</p>';
echo '</div>';
if ($i % 3 == 0) echo '</div>';
}
?>
nevermind, my bad, i figured it out just a few minutes after posting this. both
$('#card-gallery').load('cardgallery.php', function() {
$('.draggable').draggable({
containment: "document",
helper: "clone",
appendTo: 'body',
scroll: false
});
});
&
function allowDrag() {
$('.draggable').draggable({
containment: "document",
helper: "clone",
appendTo: 'body',
scroll: false
});
}
$('#card-gallery').load('cardgallery.php', allowDrag)
work.

ajax load content render in php return

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.

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