I'm trying to load more posts via load more button when it will be clicked but its not working properly my first three posts repeat again and again, anyone can help me?
Here is my query which I placed in template file.
$paged=get_query_var('paged') ? get_query_var('paged') : 1;
$the_queryx = new WP_Query(array(
'post_type' => 'exhibitions',
'posts_per_page' => 3,
'post_status' => 'publish',
'order' => 'DESC',
'paged'=>$paged,
'post__not_in'=> array($sticky_post_id),
)
);
$the_max_num_pagesx = $the_queryx->max_num_pages;
if ($the_queryx->have_posts()) {
echo '<div id="post_cat_home" class="row">';
while ($the_queryx->have_posts()) {
$the_queryx->the_post();
get_template_part('loop-templates/content', get_post_format());
}
echo '</div>';
if ($the_max_num_pagesx > 1) {
echo '<div class="load-more-posts" style="width:100%; text-align:center;">
<button id="more_posts_home_exb" data-sticky="' . $sticky_post_id . '" data-pages="' . $the_max_num_pagesx . '" data-pn="'.$paged.'" class="btn more_posts"> </button>
</div>';
}
/* Restore original Post Data */
wp_reset_postdata();
}
And here is my ajax script:
$("#more_posts_home_exb").on("click", function (e) {
e.preventDefault();// When btn is pressed.
$(this).attr("disabled", true); // Disable the button, temp.
var total = $(this).data('pages');
var sticky = $(this).data('sticky');
load_posts_home_exb(total, sticky);
});
//home exhibitions loading
function load_posts_home_exb(total, sticky) {
var pageNumber = 1;
var ppp = 3; // Post per page
var str = '&sticky_ignore=' + sticky + '&pageNumber=' + pageNumber + '&total=' + total + '&action=more_post_home_exb_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function (data) {
var $data = $(data);
pageNumber++;
if ($data.length) {
$("#post_cat_home").append($data);
$("#more_posts_home_exb").attr("disabled", false);
} else {
$("#more_posts_home_exb").attr("disabled", true);
}
},
error: function (jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
This is my final function file code which function call through via ajax script.
function more_post_home_exb_ajax()
{
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
// $paged = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
$sticky_ignore = (isset($_POST['sticky_ignore'])) ? array($_POST['sticky_ignore']) : '';
$paged = $_POST['pageNumber'] +1;
header("Content-Type: text/html");
$loop_template = 'loop-templates/content';
$args = array(
// 'suppress_filters' => true,
'post_type' => 'exhibitions',
'posts_per_page' => $ppp,
'post__not_in' => $sticky_ignore,
'order' => 'DESC',
'post_status' => 'publish',
'paged' => $paged,
);
$loop = new WP_Query($args);
$out = '';
if ($loop->have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
get_template_part($loop_template, get_post_format());
endwhile;
endif;
exit;
}
add_action('wp_ajax_nopriv_more_post_home_exb_ajax', 'more_post_home_exb_ajax');
add_action('wp_ajax_more_post_home_exb_ajax', 'more_post_home_exb_ajax');
This code works but first three posts repeat when button clicked. Thank you!
I've tried some condition in ajax script and it is working now. ;)
//home exhibitions loading
function load_posts_home_exb(total, sticky) {
var pageNumber = 0;
var ppp = 3; // Post per page
pc_x++;
pageNumber = pc_x;
if (total > pageNumber - 1) {
var str = '&sticky_ignore=' + sticky + '&pageNumber=' + pageNumber + '&total=' + total + '&action=more_post_home_exb_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function (data) {
var $data = $(data);
if ($data.length) {
$("#post_cat_home").append($data);
$("#more_posts_home_exb").attr("disabled", false);
} else {
$("#more_posts_home_exb").attr("disabled", true);
}
},
error: function (jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
}
else{
$("#more_posts_home_exb").hide();
}
return false;
}
Related
I have this "click Listener" that calls and sends a userId parameter to the function-"getModalData" which then returns an array value to the variable-"arrayedUserData".
$('body').on('click', '.openModal', function () {
var userId = $(this).val(),
btnText = $(this).text(),
btnClass = '',
colorCode = '',
arrayedUserData = getModalData(userId);
if (btnText === "Delete") {
btnClass = 'danger';
colorCode = '#d9534f';
} else {
btnClass = 'warning';
colorCode = '#f0ad4e';
}
$('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
$('#modalTitle').text('Confirm ' + btnText);
$('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
});
This is the function-"getModalData". The returned php array from the Ajax's "success" will then be passed to the variable-"UserData" that is then returned by the function.
function getModalData(passedUserId) {
var UserData;
$.ajax(
{
type: "POST",
url: "get/get_modal_data.php",
data: { passedUserId: passedUserId },
dataType: "json",
success: function (data) {
UserData = data;
}
}
);
return UserData;
}
this is the "get_modal_data.php".
<?php
include "../includes/connect.php";
if (isset($_POST['passedUserId'])) {
$UserId = mysqli_real_escape_string($con, $_POST['passedUserId']);
$getUserData = mysqli_query($con, "SELECT * FROM tblUserAccounts WHERE uaUserId = '".$UserId."'");
$uaRow = mysqli_fetch_assoc($getUserData);
$UserDataArr = array("UserId" => $uaRow['uaUserId'],
"EmailAddress" => $uaRow['uaEmailAddress'],
"FirstName" => $uaRow['uaFirstName'],
"LastName" => $uaRow['uaLastName'],
"BirthDate" => $uaRow['uaBirthDate'],
"Address" => $uaRow['uaAddress'],
"Gender" => $uaRow['uaGender'],
"ContactNumber" => $uaRow['uaContactNumber'],
"BloodTypeId" => $uaRow['uaBloodTypeId'],
"AccountStatus" => $uaRow['uaAccountStatus'],
);
echo json_encode($UserDataArr);
exit();
}
?>
this error appears on the console:
Uncaught TypeError: Cannot read property 'LastName' of undefined get_user_accounts.js:66
this is the line 66 of get_user_accounts.js, which is present on the "click listener".
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
but, I am confused because the php array appears on the browser's Network Response:
Successful Connection{"UserId":"1","EmailAddress":"paulanselmendoza#gmail.com","FirstName":"Paul Ansel","LastName":"Mendoza","BirthDate":"1998-12-17","Address":"Phase 1B Block 8 Lot 20 Olivarez Homes South, Sto. Tomas, Binan City, Laguna","Gender":"Male","ContactNumber":"2147483647","BloodTypeId":"0","AccountStatus":"ACTIVE"}
Did you see that you get: Successful Connection before the JSON data? You have to remove that, if not it will be an invalid JSON response. The code you have shared doesn't have the particular stuff.
I believe you have to check your database connection, where on successful connection, it is set to output Successful Connection, which breaks your response. Please remove that bit of code.
include "../includes/connect.php";
It can be something like:
$conn = mysqli_connect() or die("Error");
echo "Successful Connection";
Because getModalData fucntion return the UserData before it asign by ajax(UserData = data;). use a callback function:
using callbacks
function getModalData(passedUserId,callback) {
$.ajax(
{
type: "POST",
url: "get/get_modal_data.php",
data: { passedUserId: passedUserId },
dataType: "json",
success: function (data) {
callback(data);
}
}
);
}
$('body').on('click', '.openModal', function () {
var userId = $(this).val(),
btnText = $(this).text(),
btnClass = '',
colorCode = '';
getModalData(userId, function (arrayedUserData) {
if (btnText === "Delete") {
btnClass = 'danger';
colorCode = '#d9534f';
} else {
btnClass = 'warning';
colorCode = '#f0ad4e';
}
$('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
$('#modalTitle').text('Confirm ' + btnText);
$('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
});
});
My code, basically, on a click of a button, runs an ajax function in order to write stuff to my database.
What I want to do next is call another function which will fetch data from the database and print it.
Here is my code below, but the second function does not show that it works. I don't know where I went wrong.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function loaddata() {
$.ajax({
type: "POST",
url: "includes/fetchupdatedimages.php",
data: $("#editad_form").serialize(),
success: function (response) {
alert(response);
}
});
});
</script>
Second function:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$("#deleteimgs").click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "includes/deleteimages.php",
data: $("#editad_form").serialize()
});
$("input[type=checkbox]:checked").parent().remove();
loaddata();
});
});
</script>
fetchupdatedimages.php
<?php
include_once "functions.php";
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(-1);
error_reporting(E_ALL);
$id = $_POST["id"];
if ($stmt = $mysqli->prepare("SELECT images FROM db WHERE id = ? LIMIT 1")) {
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($images);
$stmt->fetch();
}
echo "<p>" . $images . "</p>";
?>
It seems that loaddata() does not get called or it does not return any data to me back. Any help?
Have you tried sending the data from your PHP file using JSON over to your jQuery code instead?
For example:
PHP
<?php
header("Content-Type: application/json");
include 'connect.php';
$sql = "SELECT * FROM reviews, customers WHERE review_user = customer_id";
$datas = "";
$x = 0;
$result = $con->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$datas[$x] = array("fname" => $row["customer_name"], "lname" => $row["customer_surname"], "email" => $row["customer_email"], "gender" => $row["customer_gender"], "title" => $row["review_title"], "content" => $row["review_content"], "rating" => $row["review_rating"]);
$x++;
}
}
$con->close();
echo json_encode($datas);
?>
jQuery
$(document).ready(function() {
$.getJSON('controls/getReviews.php', function(jsondata) {
console.log("Returned data: " + jsondata);
if (jsondata !== "") {
for (var i = 0; i < jsondata.length; i++) {
var data = jsondata[i];
var fname = data["fname"];
var lname = data["lname"];
var email = data["email"];
var gender = data["gender"];
var title = data["title"];
var msg = data["content"];
var rating = data["rating"];
$('.reviews').append('<div class="panel panel-default"><div class="panel-heading"><h3 class="panel-title">' + title + '</h3></div><div class="panel-body"><table class="table table-striped"><tr><td>Name:</td><td>' + fname + ' ' + lname + '</td></tr><tr><td>Gender:</td><td>' + gender + '</td></tr><tr><td>Rating:</td><td>' + rating + '/5</td></tr><tr><td>Message:</td><td>' + msg + '</td></tr></table></div></div>');
}
}
});
});
Hi I am stuck in building the pagination of my comment in a certain topic. At first I use ajax with custom appending of html tags but I find out later I cannot echo or print the cake Form helpers on the view. Anyone here can give some idea of how to do it?
This is my Controller code
public function view($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid topic'));
}
$topic = $this->Topic->viewTopicAndComments($id);
// echo "<pre>";
// print_r($topic);
// exit;
if (empty($topic))
{
$topic[0] = $this->Topic->viewById($id);
}
if (!$topic) {
throw new NotFoundException(__('Invalid topic'));
}
$this->set('topic', $topic);
}
While in my Model
public function viewTopicAndComments($id)
{
return $this->Comment->find('all', array(
'conditions' => array(
'Topic.id' => $id,
'Topic.deleted_flag' => ACTIVE_FLAG,
'Comment.deleted_flag' => ACTIVE_FLAG,
),
'fields' => array(
'Topic.id',
'Topic.title',
'Topic.content',
'Topic.created',
'User.id',
'User.firstname',
'User.lastname',
'User.middlename',
'Comment.content',
'Comment.user_id',
'Comment.id',
'Comment.created',
),
'limit' => 5,
'order' => array('Comment.created DESC'),
)
);
}
And in my custom js for ajax
$(document).ready(function(){
$('.right_col').scroll(function(){
var scrollTop = $(this).scrollTop(),
innerHeight = $(this).innerHeight(),
documentElement = $(this)[0].scrollHeight,
rowCount = $('#rowCount').val(),
topic = $('#topic_id').val();
if (scrollTop + innerHeight >= documentElement)
{
// var counter = 0,
// comment_id = 0;
$.ajax({
type: 'get',
url: '/comments/fetch_comments/'+ rowCount +'/'+ topic,
cache: 'false',
dataType: 'JSON',
contentType: 'application/json; charset=utf-8',
beforeSend: function()
{
$('.loader-container').css('display','block');
},
success: function(response)
{
$('.loader-container').css('display','none');
if (response[0] !== undefined)
{
for (var i in response)
{
console.log(response[i]['Comment']);
console.log(response);
var newVal = parseInt(rowCount) + 5;
var html = "<div class='row'>"+
"<div class='col-md-12'>"+
"<div class='x_panel'>"+
"<div class='comment_wrapper'>"+
"<div class='comment_profile_pic'>"+
"<img src='/custom/images/user.png' alt='avatar'/>"+
"</div>"+
"<div class='content'>"+
"<a><b>"+ escapeHtml(response[i]['User'].lastname.capitalize()) +', '+ escapeHtml(response[i]['User'].firstname.capitalize()) +' '+ escapeHtml(response[i]['User'].middlename.capitalize()) +"</b></a>"+
"<a class='timestamp'> "+ response[i]['Comment'].created +"</a>"+
"</div>"+
"</div>"+
"</div>"+
"</div>"+
"</div>";
$('#rowCount').val(newVal);
$('#comment-block').append(html);
}
}
}
});
}
});
String.prototype.capitalize = function()
{
return this.charAt(0).toUpperCase() + this.slice(1);
}
function escapeHtml(text) {
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
});
guys i keep on getting this uncaught syntaxerror:unexpected token <, and it points to the jquery library file,i am making a request to AJAX(comment-insert-ajax.php) using JQuery(comment-insert.js),i try removing the closing token of php(?>) in the AJAX script but i still get the error.I actually get the error when i add the 'require_once' lines,sorry about that.
comment-insert-ajax.php
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-insert')
{
$userId = (int)$_POST['userId'];
$comment = addslashes(str_replace("\n","<br>",$_POST['comment']));
$std = new stdClass();
$std->comment_id = 24;
$std->userId = $userId;
$std->comment = $comment;
$std->userName = "Thabo Ambrose";
$std->profile_img= "images/tbo.jpg";
require_once $_SERVER['DOCUMENT_ROOT'] . 'defines.php';
require_once MODELS_DIR . 'Comments.php';
echo json_encode($std);
}
else
{
header('location: /');
}
and following is the Jquery file that makes the request using the '$.post' method.
comment-insert.js
$(document).ready(function(){
$('#comment-post-btn').click(function(){
comment_post_btn_click();
});
});
function comment_post_btn_click()
{
var _comment = $('#comment-post-text').val();
var _userId = $('#user-id').val();
var _userName = $('#user-name').val();
if(_comment.length > 0 && _userId != null)
{
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(jQuery.parseJSON(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}
else
{
//do something
$('#comment-post-text').addClass('alert alert-danger');
$('#comment-post-text').focus(function(){$('#comment-post-text').removeClass('alert alert-danger');});
}
//remove text in the text area after posting
$('#comment-post-text').val("");
}
function comment_insert(data)
{
var t = '';
t += '<li class="comment-holder" id="_'+data.comment_id+'">';
t += '<div class="user-img">';
t += '<img src="'+data.profile_img+'" class="user-img-pic">';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field">'+data.userName+'</h3>';
t += '<div class="comment-text">'+data.comment+'</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">x</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}
The error points to line 7497 of the jQuery library,it point to the following code
jQuery.parseJSON = function(data)
{
return data;
}
Try using the JSON.parse function:
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(JSON.parse(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}
try puting the data in a array and then encode it
$array = ['comment_id' => 24,'userId' => $userId,'comment' => $comment,'userName' => "Thabo Ambrose",'profile_img'= "images/tbo.jpg"];
echo json_encode($array);
change if(isset($_POST['task']) && $_POST['task'] == 'comment-insert') this line of code to if(isset($_POST['task']) && isset($_POST['task'])&&$_POST['task']== 'comment-insert').
then change the ajax call to
$.ajax({
url: "ajax/comment-insert-ajax.php",
data :{"task":"comment-insert","UserId":_userId,"comment":_comment},
type: "POST",
dataType: "json",
success:function(msg) {
}
});
Ajax
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '../include/ListOfCities.php',
dataType: "json",
data: {
Country: "Japan"
},
success: function(data) {
console.log(data);
var city = ('#city');
$(city).empty();
for (var i = 0; i < data.length; i++) {
$(city).append('<option id=' + data[i].sysid + ' value=' + data[i].city_name + '>' + data[i].city_name + '</option>');
}
}
});
});
php
$country = mysql_real_escape_string($_POST['Country']);
$stmt = $dbh->prepare("SELECT * FROM city_tbl WHERE country_name = ? ");
$stmt->bindValue(1, $country, PDO::PARAM_STR);
if ($stmt->execute()) {
if ($stmt->rowCount() > 0) {
while ($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$citylist[] = array('sysid' => $selected_row['sys_id'], 'code' => $selected_row['city_code'], 'name' => $selected_row['city_name'], 'parentid' => $selected_row['parent_id']);
}
$input = array_map("unserialize", array_unique(array_map("serialize", $citylist)));
echo json_encode($input, JSON_UNESCAPED_UNICODE);
}
}
I want to display the all the city in japan in a select option menu i want to load the cities when the page loads i am sending the ajax request like above but i don't get any result the ajax above works fine when i use it on button. Is sending ajax request different from on button click and on document ready..Any suggestion how to make ajax request on document ready is appreciated
Just try setting async:false in your ajax request. So the final code will be
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '../include/ListOfCities.php',
dataType: "json",
async:false,
data: {
Country: "Japan"
},
success: function(data) {
console.log(data);
var city = ('#city');
$(city).empty();
for (var i = 0; i < data.length; i++) {
$(city).append('<option id=' + data[i].sysid + ' value=' + data[i].city_name + '>' + data[i].city_name + '</option>');
}
}
});
});