Show more result from database with jQuery and AJAX - php

I'm trying to create news block with AJAX in my template. so i wrote a simple code, in HTML Part:
Show Posts
<div id="result"></div>
jQuery Part:
function ShowPost(){
$.post(dir + 'engine/ajax/posts.php', {action:"showpost"},
function(data) {
$("#result").html(data);
});
};
PHP Part:
if ($_POST['action'] == "showpost") {
$db->query( "SELECT title FROM post LIMIT 0,5 " );
while ( $row = $db->get_row() ) {
echo $row['title']."<br>";
}
}
Question is, how i can get more result after first click? for example, after first click on Show Posts link, i can show the 5 news from database. after second click on Show Posts link i need to show 6 to 10 news, in third click get result from 11 to 15 and continue ...
i hope you understand my question.

Based on your implementation you need to keep track how many items you have shown and pass the page number in. For example:
jQuery Part:
var pageNumber = 0;
function ShowPost() {
pageNumber++;
$.post(dir+ 'engine/ajax/posts.php', {action:"showpost", pageNum: pageNumber},
function(data) {
$("#result").html(data);
});
};
Disclaimer: I m not a PHP developer so please treat teh code below as pseudo-code.
PHP Part:
if ($_POST['action'] == "showpost") {
var pageSize = 5;
var pageNumber = $_POST['pageNumber'];
var from = (pageNumber - 1) * pageSize;
var to = pageNumber * pageSize;
$db->query( "SELECT title FROM post LIMIT " + from + "," + pageSize);
while ( $row = $db->get_row()) { echo $row['title']."<br>"; }
}

Just implement the pagination limit in ur query
var offset = -5;
function ShowPost(){
offset = offset + 5;
$.post(dir + 'engine/ajax/posts.php', {action:"showpost",offset:offset},
function(data) {
$("#result").html(data);
});
};
PHP part
if ($_POST['action'] == "showpost") {
$vOffset = $_POST['offset'];
$db->query( "SELECT title FROM post LIMIT $vOffset,5 " );
while ( $row = $db->get_row() ) {
echo $row['title']."<br>";
}
}

Take a hidden field in html and update it's value after every success call and when next time you call for next record send that value in post.
<input type="hidden" name="limit" value="5">
Show Posts
<div id="result"></div>

Related

want to diplay ads from my database if ads not found than chitika code ads display

This is my code. please add if else statement in this code. As if ads found in my database than ads display from database otherwise chitika code ads display. no this code display both ads first display ads from my database and then from chitika code ads. please add if else statement. because i have no idea how to apply if else in this matter.
<div style="margin-left:-7px ! important;">
<?php
$sql4 = "SELECT * FROM abc ORDER BY id DESC LIMIT 1";
$query4 = $conn->query($sql4);
$row4 = $query4->fetch(PDO::FETCH_ASSOC);
$link4 = $row4['link_url'];
$images4 = $row4['imagepath'];
$immg4 = basename($images4);
$imagee4 = "adverts"."/".$immg4;
$rowc = $query4->rowCount(PDO::FETCH_ASSOC);
if ($rowc>=1){
echo "
<a href='$link4'; target='_blank'><img src='$imagee4';></a>";
}
else {
echo "";
}
?>
<script type="text/javascript">
( function() {
if (window.CHITIKA === undefined) { window.CHITIKA = { 'units' : [] }; };
var unit = {"calltype":"async[2]","publisher":"seeknfameads","width":300,"height":250,"sid":"Chitika Default","color_site_link":"337ab7","color_text":"337ab7"};
var placement_id = window.CHITIKA.units.length;
window.CHITIKA.units.push(unit);
document.write('<div id="chitikaAdBlock-' + placement_id + '"></div>');
}());
</script>
<script type="text/javascript" src="//cdn.chitika.net/getads.js" async> </script>
</div>
please write code again with if else. as i copy paste into my page. thanks in advance.
It seems you are asking how if/else works in php.
if else is used to execute some code when a statement is true and another one if it is false.
If you define a function to get the number of ads from your database and a function to display the ads from your database and a function to display the ads from Chikita then your code might look like this:
if(getNumberOfAdsInMyDB() > 0){
displayAdsFromDatabase();
}
else {
displayAdsFromChikita();
}
This will only execute the function displayAdsFromDatabase() if getNumberOfAdsInMyDB() returns a value that is bigger than 0 and will only execute the function displayAdsFromChikita() when getNumberOfAdsInMyDB() returns a value that is not bigger than 0.

Ajax search and pagination

I have this AJAX pagination code.
$('document').ready(function() {
$("#pagination a").trigger('click'); // When page is loaded we trigger a click
});
$('#pagination, #searchButton').on('click', 'a', function(e) { // When click on a 'a' element of the pagination div
e.preventDefault();
var page = this.id; // Page number is the id of the 'a' element
var pagination = ''; // Init pagination
$('#articleArea').html('<img src="images/ajax-loader.gif" alt="" />'); // Display a processing icon
var data = {term: term, page: page, per_page: 9}; // Create JSON which will be sent via Ajax
// We set up the per_page var at 4. You may change to any number you need.
$.ajax({ // jQuery Ajax
type: 'POST',
url: 'includes/fetch-pages.php', // URL to the PHP file which will insert new value in the database
data: data, // We send the data string
dataType: 'json', // Json format
timeout: 3000,
success: function(data) {
$('#articleArea').html(data.articleList); // We update the page with the event list
console.log(data.num);
// Pagination system
if (page == 1) pagination += '<div class="cell_disabled"><span>Primero</span></div><div class="cell_disabled"><span>Anterior</span></div>';
else pagination += '<div class="cell">Primero</div><div class="cell">Anterior</span></div>';
for (var i=parseInt(page)-3; i<=parseInt(page)+3; i++) {
if (i >= 1 && i <= data.numPage) {
pagination += '<div';
if (i == page) pagination += ' class="cell_active"><span>' + i + '</span>';
else pagination += ' class="cell">' + i + '';
pagination += '</div>';
}
}
if (page == data.numPage) pagination += '<div class="cell_disabled"><span>Siguiente</span></div><div class="cell_disabled"><span>Último</span></div>';
else pagination += '<div class="cell">Siguiente</div><div class="cell">Último</span></div>';
$('#pagination').html(pagination); // We update the pagination DIV
},
error: function() {
}
});
return false;
});
Now I want to add a search form:
<form class="form-inline col-xs-12 col-sm-5 col-md-4 hidden-xs" id="searchFormTop">
<div class="row buscar">
<div class="form-group col-xs-9">
<input type="text" placeholder="" class="form-control" name="searchTerm" id="searchTerm" value="test">
</div>
<button type= "submit" class="btn col-xs-3" id="searchButton"> BUSCAR </button>
</div>
</form>
How can I get the value from the form and pass it to the AJAX call? I'm trying to add another event to trigger the ajax call when the form in submited and then get the search term value using val(), but I cannot make in work.
$('document').ready(function() {
$("#pagination a").trigger('click'); // When page is loaded we trigger a click
});
$('#pagination, #searchFormTop').on('click', 'a', function(e) { // When click on a 'a' element of the pagination div
e.preventDefault();
var page = this.id; // Page number is the id of the 'a' element
var pagination = ''; // Init pagination
var term = $('#searchTerm').val();
The PHP code processing the request is:
$page = $_POST['page']; // Current page number
$per_page = $_POST['per_page']; // Articles per page
if ($page != 1) $start = ($page-1) * $per_page;
else $start=0;
$today = date('Y-m-d');
$term = $_POST['searchTerm']; // Current page number
// Select items list from $start.
// An item might have multiple categories. A regular join query will create a row for each category
//so that the event will be displayed as many times as categories it has.
//To group all the caegories in one single result, we can use GROUP_CONCAT and then, GROUP BY
$sql = "SELECT *, events.name AS event_name, -- THIS WILL the defferesnt categories on on eevent
GROUP_CONCAT(DISTINCT catevent.cat_id) as cats,
GROUP_CONCAT(DISTINCT categories.name SEPARATOR ', ') as cat_names
FROM events
LEFT JOIN catevent
ON catevent.event_id=events.event_id
LEFT JOIN categories
ON catevent.cat_id=categories.id
LEFT JOIN images
ON images.item_id=events.event_id
WHERE categories.parent_cat != 0
AND publish=1 AND images.item_type_id=1 AND images.img_name NOT LIKE '%sm%' -- We want to get only the name of the regular img for each event
AND final_date >= '$today'
GROUP BY events.event_id -- Needed to display all the events
ORDER BY events.initial_date ASC, events.initial_date DESC, events.name ASC
LIMIT $start, $per_page";
$select=$pdo->query($sql);
$select->setFetchMode(PDO::FETCH_OBJ);
$results = $select->fetchAll();
// Total number of articles in the database
$numArticles = $pdo->query("SELECT count(event_id) FROM events WHERE publish=1 AND final_date >= '$today'")->fetch(PDO::FETCH_NUM);
$numPage = ceil($numArticles[0] / $per_page); // Total number of page
// We build the article list
$articleList = '';
foreach( $results as $result) {
//Get final month, year, and day from date stored in db
$date_from_db=test_output($result->final_date);
$time=strtotime($date_from_db);
$year= date('Y', $time);
$year_short= substr($year,2);
$month=date('n', $time);
$day=date('j', $time);
//Get initial month, year, and day from date stored in db
$date_from_db_i=test_output($result->initial_date);
$time_i=strtotime($date_from_db_i);
$year_i= date('Y', $time_i);
$year_short_i= substr($year_i,2);
$month_i=date('n', $time_i);
$day_i=date('j', $time_i);
//get the sm image name
$lg_image=test_output($result->img_name);
$images_names=get_img_names($lg_image);
$img_sm= $images_names['regular_sm'];
//default event slug
$event_slug=test_output($result->slug);
if (empty($result->slug)||$result->slug=="default" ){
$slug=$result->event_id;
}
//get parent cat name
$parent_cat_id=test_output($result->parent_cat);
$parent_cat_name=cat_name($parent_cat_id);
//if there are several cats for one event, display them
if (isset($result->cat_names)){
$subcat=test_output($result->cat_names);
}else{
$subcat=test_output($result->name);
}
//$articleList .= '<div class="well well-sm">' . $result->id . '. <b>' . $result->title . '</b><p>' . test_output($result->description) . '</p></div>';
include('event-item-agenda.php');
}
// We send back the total number of page and the article list
$dataBack = array('numPage' => $numPage, 'articleList' => $articleList, 'num'=>$numArticles, 'term'=>$term);
$dataBack = json_encode($dataBack);
echo $dataBack;
Maybe, you guys, can help me see what I'm doing wrong.
Thanks in advance
Sonia

PHP loading items from the database into a div on load more button click

I have a main.php page where I have a while loop that displays the first 10 items from the database. I want to load the next 10 items once a load more button is clicked.
$res = mysql_query("SELECT * FROM `posts` ORDER BY `date` DESC LIMIT 10");
if($res && mysql_num_rows($res) > 0){
while($row = mysql_fetch_assoc($res)){
$id = $row['id'];
?>
<div class="main_page">
item id <?php echo $id; ?>
</div>
<button class="load_more">Load More</button>
....
What is a good way of doing this? Any help is much appreciated!
UPDATE:
right now i have this script for the load more button:
<script type="text/javascript">
$(document).ready(function(){
$(".load_more").click(function (){
$('.load_more').html('<img src="images/ajax-loader.gif" />');
$.ajax({
url: "loadmore.php?id=" + $(".ad_display:last").attr("id"),
success: function(html){
if(html){
$(".main_page").append(html);
$('.load_more').html('Load More');
}else{
$('.load_more').replaceWith('No posts');
}
}
});
});
});
</script>
after the form of the filters is submitted, the url looks somewhat like this:
index.php?search=&category=0&ad_order=1
how do I pass on the search (even if empty), ad_order, and category value to the loadmore.php?
limit 0, 10 will display the first 10 items from your query. limit 20,10 will display 10 items starting with the 20th item (counting from zero). You can pass the page number or the number of items retrieved up to now in a parameter when you call the page that does the query. This will involve either reloading the current page with a different start index in limit, or issuing an ajax query that lets you load more items without reloading the page.
Apart from the answer posted by Octern, not sure what you want to achieve for your second question but try:
<script type="text/javascript">
//saving the GET variables
ad = <?php echo $_GET['ad_order']; ?>
catg = <?php echo $_GET['category']; ?>
search = <?php echo $_GET['search']; ?>
//default value of record to start from
rec = 0;
$(document).ready(function(){
$(".load_more").click(function (){
$('.load_more').html('<img src="images/ajax-loader.gif" />');
$.ajax({
//passing them here
//URL updated to pass rec
url: "loadmore.php?id=" + $(".ad_display:last").attr("id")+"&search="+search+"&category="+catg+"&ad_order="+ad+"&rec="+rec,
success: function(html){
//updating counter to start from record
rec += 10;
if(html){
$(".main_page").append(html);
$('.load_more').html('Load More');
}else{
$('.load_more').replaceWith('No posts');
}
}
});
});
});
</script>
In your loadmore.php you need to relevant code to fetch the above $_GET values
Your query will be something like:
$res = mysql_query("SELECT * FROM classifieds WHERE date < '".mysql_real_escape_string($_GET['id'])."' AND search = '".$_GET['search']."' AND category = '".$_GET['category']."' AND ad_order = '".$_GET['ad_order']."' ORDER BY date DESC LIMIT '".$_GET['rec']."',10");
So everytime you click on the load_more, the limit will change as LIMIT 0,10 -> LIMIT 10,10 -> LIMIT 20,10 etc.

get contents with ajax and display them directly without refreshing the page

I have created a blog in php. For each comment the user can press a Favorite/Unfavorite button (if want) to Favorite/Unfavorite a post. My button works perfect. The only problem I got is that when user press Favorite/Unfavorite... I dont get the number of Favorites/Unfavorites for this post. In order to get this, each time I have to refressh the page. Some people told me that I need to use Ajax in order to do this.
I use table likes, to hold favorites for each post: likes(like_id, user, the_comment_id)
I use table comments for aeach post: comments(comments_id, comment, user)
This is my php code:
<?php
$comment_id = $row['comments_id'];
// ... code above
//button for favorite and unfavorite
$get_button = mysql_query(" SELECT * FROM `likes` WHERE `user`='$session_user_id' AND `the_comment_id`='{$row['comments_id']}' ");
$get = mysql_fetch_assoc($get_button);
if($get==""){
$comments .= "<a role='button' class='button' id='like$comment_id' style='color:grey;'>Favorite</a>";
}else if($get!=""){
$comments .= "<a role='button' class='button' id='unlike$comment_id' style='color:grey;'>Unfavorite</a>";
}
// place favorites for this comment here
$comments .= " $total_favorites ";
?>
This is my jquery:
<script>
$(document).ready(function(){
$("#like<?php echo $comment_id; ?>").click(function() {
var id = "<?php echo $comment_id; ?>";
$.post("parse.php",{like:id}, function(data){
$("#like<?php echo $comment_id; ?>");
$(".button<?php echo $comment_id; ?>").html(data);
});
$(this).hide().attr("Disabled", "True").text("Favorite done!").show();
});
$("#unlike<?php echo $comment_id; ?>").click(function() {
var id = "<?php echo $comment_id; ?>";
$.post("parse.php",{unlike:id}, function(data){
$("#unlike<?php echo $comment_id; ?>");
$(".button<?php echo $comment_id; ?>").html(data);
});
$(this).hide().attr("Disabled", "True").text("Unfavorite done!").show();
});
});
</script>
This is my parse.php code:
<?php
if(isset($_POST['like'])){
$id = $_POST['like'];
mysql_query("INSERT INTO likes VALUES ('', '$session_user_id', '$id') ");
}
if(isset($_POST['unlike'])){
$id = $_POST['unlike'];
mysql_query(" DELETE FROM likes WHERE `user`='$session_user_id' AND `the_comment_id`='$id' ");
}
$favorites = mysql_query(" SELECT * FROM `likes` WHERE `the_comment_id`='{$row['comments_id']}' ");
$total_favorites = mysql_num_rows($favorites);
?>
You would need to return something from the parse.php script. The data variable will not contain the count unless you either echo it out directly or return JSON and parse in your jQuery function prior to setting the .html(data) values.
You are right, AJAX is the way to go. Note that AJAX is known by multiple names:
XMLHttpRequest -- javascript
AJAX
$.ajax() -- the jQuery superset
$.get() -- a shortcut to $.ajax() with TYPE: "GET"
$.post() -- a shortcut to $.ajax() with TYPE: "POST"
$.load() -- see Difference between $("#id").load and $.ajax?
Here are some examples that will get you started on AJAX:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
Further to what Lucas said, change your code to look like this:
<?php
if(isset($_POST['like'])){
$id = $_POST['like'];
mysql_query("INSERT INTO likes VALUES ('', '$session_user_id', '$id') ");
}
if(isset($_POST['unlike'])){
$id = $_POST['unlike'];
mysql_query(" DELETE FROM likes WHERE `user`='$session_user_id' AND `the_comment_id`='$id' ");
}
$favorites = mysql_query(" SELECT * FROM `likes` WHERE `the_comment_id`='{$row['comments_id']}' ");
$total_favorites = mysql_num_rows($favorites);
$out = '<h1>Found In Database</h1>';
$out .= '<p>You received ' .$total_favorites. ' favorites.';
echo $out;
?>
If this doesn't work, then please post the relevant HTML so that we can accurately target your DOM elements:
$(document).ready(function(){
$("[id^=like]").click(function() {
var window.id = $(this).attr('id').split['e'][1];
$.post("parse.php",{like:id}, function(data){
$("#like"+id).find(".button").html(data);
}); //END .post
$(this).hide().attr("Disabled", "True").text("Favorite done!").show();
}); //END like.click
$("[id^=unlike]").click(function() {
var window.id = $(this).attr('id').split['e'][1];
$.post("parse.php",{unlike:id}, function(data){
$("#unlike"+id).find(".button").html(data);
}); //END .post
$(this).hide().attr("Disabled", "True").text("Unfavorite done!").show();
}); //END #unlike.click
});
Notes:
We use $("[id^=unlike]") as the selector - this means: get the DOM element with an ID that starts with "unlike"
$(this).attr('id').split['e'][1] means:
a. Get the ID attribute ("like5" or "unlike123")
b. Break it into an array at teh 'e' char: lik and 5 -or- unlik and 123
c. Grab the 2nd array element (the number: 5 or 123)
d. Stick it in a global variable called id

Saving sortable to mysql with ajax jquery and php

I have a page with multiple drag&drop boxes, that works great, the thing that does not work are the links in the boxes. I would appreciate if someone could help me :). So I have a page where people can drag&drop boxes (it works fine, as I said before), the links inside the boxes are sortable aswell, but I can't seem to get them to save the values to mysql. I think there is a conflict between the two drag&drops, maybe I am doing it wrong, 'cause I haven't used ajax and jquery before.
//here is the jquery where I need to add some ajax
$(function() {
$('.dragbox-content').sortable({
connectWith: '.dragbox-content',
update: function(event, ui) {
var order=$(this).attr('id');
alert(order); // I get the order alert and it has one value that I need, but I need the sort order aswell
}
});
});
//this is the <div> that has the links in them and mysql query that gets the values
//from two different databases, one is for the boxes and the other for links.
//boxes db id = links title_id
echo '<div class="dragbox-content" id="order'.$widget['id'].'"';'>''</div>';
$sql10 = "SELECT u.*, w.id, w.link_address, w.link_name FROM db_boxes u LEFT
JOIN db_links w ON u.link_id = w.id WHERE
(u.username = '$username' AND u.link_id !='0' AND w.title_id = '".$widget['id']."'
AND w.link_name !='pilt' AND w.rights = '0') OR
(u.username = '$username' AND u.link_id !='0' AND w.title_id = '".$widget['id']."'
AND w.link_name !='pilt' AND w.rights LIKE '%26%') ORDER BY w.id ASC";
$result10 = mysql_query($sql10) or die (mysql_error());
while ($row = mysql_fetch_array($result10)) {
$link_id = $row['id'];
$link_address = $row['link_address'];
$link_name = $row['link_name'];
$title_id = $row['title_id'];
?>
<div class="move" id="<?php echo $link_id;?>">
<span class="link_style">
<div><?php echo $link_name;?> </div</span></div>
I just need somebody to tell me how can I save tile_id and sort_order to boxes database with ajax on every click a user makes on that page
See my example below:
http://jsfiddle.net/gRoberts/vMy7r/
$(function () {
$('ul').sortable({
update : function(e, ui) {
var ul = $(ui.item).closest('ul');
var index = 0;
var toPost = {};
ul.find('> li').each(function() {
index++;
$(this).find('input').val(index);
toPost[$(this).find('input').attr('name')] = index;
});
$.ajax({
url : '/echo/json/',
data : toPost,
type : 'POST',
dataType : 'json',
success : function(resp) {
alert(resp);
},
error : function() {
alert('There was a problem');
}
});
}
});
});
​
The above example can be used in two ways, if you remove the $.ajax it will update hidden form fields which you can then post normally.

Categories