Retrieving and appending HTML using PHP and Ajax - php

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

Related

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.

Load more data from database with Codeigniter and Ajax

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

Clearing a DB call after you close modal

On my about the artist page when you click on the words button, and the will open a modal that gets information from a DB. Right now when you click on one artist button, close the modal, and then click on another artist both artist information will pop up. What I am trying to do is make sure the information only shows one artist at a time. I'm not sure if there is an issue with my ajax, or my model.
Here is a link to my live site now
Model
<?php
class Artist_get_model extends CI_Model {
function getData() {
// $query = $this->db->get_where("artist_content", array(" " => $page));
$query = $this->db->query("SELECT * from artist_content");
return $query;
}
// FIRST LAST NAME
// MODEL CHANGES
// SELECT * from artist_content" where lastname =
function modalData($lastname) {
$query = $this->db->query("SELECT * FROM artist_content WHERE last_name = '$lastname'");
return $query;
// return $lastname;
}
}
?>
PHP Artist Page
<?php
// echo $query->num_rows();
echo '<div class="container">';
echo '<div style="margin-top: 13%;" class=" artistHeader page-header">';
echo '<h1>Meet the artist</h1>';
echo '</div>';
echo '</div>';
echo '<div class="panel panel-default profile">';
echo ' <div class="panel-body">';
echo '<div class="container-fluid">';
echo '<div class="row">';
for( $i = 0 ; $i < $query->num_rows() ; $i++ ){
$row = $query->row_array($i);
// echo $row['workLink_img2'];
// for()
// echo '<div class="row"';
echo '<div id="noPadding" class="col-md-4">';
echo '<div class="thumbnail noPadding">';
// PROFILE IMG
echo '<img src="'.$row['profile_img'].'" alt=""></img>';
echo '<div class="caption">';
// NAME
echo '<h3 class="artistName">'.$row['first_name'].' '.$row['last_name'].'</h3>';
echo '<p><a class="button btn btn-primary " id="hello" role="button" data-toggle="modal" data-target="#myModal" data-artist="'.$row['last_name'].'">Words</a>';
echo '</div>';
echo '</div>';
echo "</div>";
// echo "</div>";
// Modal
// Modal content
echo '<div id="myModal" class="modal fade" role="dialog">';
echo '<div class="modal-dialog modal-lg">';
echo '<div class="modal-content">';
echo '<div class="modal-header">';
echo '<button type="button" class="close" data-dismiss="modal">×</button>';
// GET NAME FROM DB
echo '<h4 class="modal-title">'.$row['first_name'].' '.$row['last_name'].' </h4>';
echo '</div>';
echo '<div class="modal-body">';
echo '<div class=" artistInfo containter-fluid">';
// LOAD PHP FILE
echo '</div>';
echo '</div>';
echo '<div class="modal-footer">';
echo '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
<script>
$(document).ready(function(){
$(".button").one("click", function(){
$.ajax({
type: "POST",
url: "/Artists/modal",
data: ({lastname: $(this).attr("data-artist") }),
success: function(result){
$(".artistInfo").append(result);
}});
});
});
Modal
<?php
for( $i = 0 ; $i < $artist->num_rows() ; $i++ ){
$row = $artist->row_array($i);
echo '<img class="pull-left img-responsive col-md-8" src=" '.$row['profile_img'].' ">';
echo '<div class="row">';
// SIDE IMG
echo '<a href="'.$row['workLink_img1'].'">';
echo '<img id="partsIm "class=" col-sm-4 pull-left img-thumbnail" src="'.$row['work_img1'].'"></img>';
echo '</a>';
// SIDE IMG
echo '<a href="'.$row['workLink_img2'].'">';
echo '<img id="partsIm" class="col-sm-4 pull-left img-thumbnail" src="'.$row['work_img2'].'"></img>';
echo '</a>';
// TEXT
echo '<p style="clear:both">'.$row['text'].'</p> ';
echo '</div>';
echo '</div>';
}
?>
It's in your button click event:
$(".button").one("click", function(){
$.ajax({
type: "POST",
url: "/Artists/modal",
data: ({lastname: $(this).attr("data-artist") }),
success: function(result){
//you're appending multiple data here
// $(".artistInfo").append(result);
// this instead:
$(".artistInfo").html(result);
}
});
});
});
lets empty it first since ajax can have a time lag...that way any time it takes to get new data it won't be displaying old data:
$(".button").on("click", function(){
$(".artistInfo").empty();// clear old html out
$.ajax({
type: "POST",
url: "/Artists/modal",
data: ({lastname: $(this).attr("data-artist") }),
success: function(result){
$(".artistInfo").append(result);
}});
});
append() adds to existing html and does not remove it thus you kept adding each time. If element is empty it won't matter what insertion method is used
NOTE: switched to on() instead of one() which is only intended to be used for a single event

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.

Order foreach results into 2 columns

I am attempting to style a list of results from a foreach into two columns, however I'm not too sure how to go about it without throwing off the PHP.
Currently, everything looks like below:
and I would like it to look so:
Currently, my foreach and CSS looks thus:
<p class="title">Reviews</p>
<section id="reviews">
<ul class="section_body">
<?php
foreach($reviews['reviews'] as $rv){
if ($rtmp++ < 10);
if ($rv['freshness'] == 'fresh') {
$image = "fresh";
}
else {
$image = "rotten";
}
echo '<img src="assets/images/' . $image . '.png" class="rating" title="Rotten" alt="Rotten" />';
echo '<li>' . $rv['quote'] . '</li>';
}
?>
</ul>
</section>
Thank you in advance to anyone who may be able to help! It will be very gratefully received.
I normally use css to do this kind of task to let the browser take care of stuffs
#reviews li
{
float:left;
width: 45%;
...
}
add those 2 lines to your css and let browser takes care of the arrangement. The idea is having each li take half of the container (50%). I made it 45% to take care of extra padding, margin and border
Also, your quote and image should be in the li
<li> <img src="..." /> <span>my quote here</span> </li>
Try below code
<section id="reviews">
<?php
$i=0;
foreach($reviews['reviews'] as $rv)
{
if($i++%2 == 0)
{
echo '<ul class="section_body">';
}
if ($rtmp++ < 10);
if ($rv['freshness'] == 'fresh') {
$image = "fresh";
}
else {
$image = "rotten";
}
$img = '<div><img src="assets/images/' . $image . '.png" class="rating" title="Rotten" alt="Rotten" /></div>';
echo '<li>' .$img . $rv['quote'] . '</li>';
if($i%2 == 0 || $i== count($reviews['reviews']))
{
echo '</ul>'
}
}
?>
</section>
You should put image and review text inside the li element.

Categories