Loading more posts not working - javascript

I am adding a LoadMore function to append more posts based on the length of current displayed posts and total posts in DOM. The issue I am having is when I console log the listofposts and I inspect the element in Google Chrome, I see the length is showing zero (0). I am not sure exactly where I have gone wrong or if the aproach I have taken is right or should I separate the two functions by first loading the first 4 posts, then create a new function separate to handle the appending?
$(document).on('pagebeforeshow', '#blogposts', function() {
//$.mobile.showPageLoadingMsg();
$.ajax({
url: "http://howtodeployit.com/category/daily-devotion/?json=recentstories&callback=",
dataType: "json",
jsonpCallback: 'successCallback',
async: true,
beforeSend: function() { $.mobile.showPageLoadingMsg(true); },
complete: function() { $.mobile.hidePageLoadingMsg(); },
success:function(data){
var $listofposts = $('data');
console.log($listofposts);
var $loadMore = $listofposts.parent().find('.load-more');
// console.log($loadMore);
currentPage = 0;
postsPerPage = 4;
var showMorePosts = function () {
$offset = currentPage * postsPerPage, //initial value is 0
posts = data.posts.slice($offset, $offset + postsPerPage);
console.log(posts);
$.each(posts, function(i, val) {
//console.log(val);
$("#postlist").html();
var result = $('<li/>').append([$("<h3>", {html: val.title}),$("<p>", {html: val.excerpt})]).wrapInner('');
$('#postlist').append(result);
console.log(result);
});
if(posts.length !== postsPerPage){
alert ('True');
$loadMore.hide();
}
currentPage++;
$("#postlist").listview();
$("#postlist").listview('refresh');
}
showMorePosts();
$loadMore.on('click', showMorePosts);
}});

var $listofposts = $('data');
is asking jQuery for a list of all <data> tags in the document.
You might want to use $(data) instead.

Related

Ajax if more then one #mention

I am trying to make a facebook and twitter style mention system using jquery ajax php but i have a problem if i try to #mention more then one user. For example if i start to type something like the follow:
Hi #stack how are you.
The results showing #stack but if i try to mention another user like this:
Hi #stack how are you. i am #azzo
Then the results are nothing. What i am missing my ajax code anyone can help me please ?
I think there is a regex problem for search user_name. When i write some username after first one like #stack then the ajax request posting this:
f : smen
menFriend : #stack
posti : 102
But if i want to tag my other friend in the same text like this:
Hi #stack how are you. I am #a then ajax request looks like this:
f : smen
menFriend : #stack, #a
posti : 102
So what I'm saying is that apparently, ajax interrogates all the words that begin with #. It needs to do is interrogate the last #mention from database.
var timer = null;
var tagstart = /#/gi;
var tagword = /#(\w+)/gi;
$("body").delegate(".addComment", "keyup", function(e) {
var value = e.target.value;
var ID = e.target.id;
clearTimeout(timer);
timer = setTimeout(function() {
var contents = value;
var goWord = contents.match(tagstart);
var goname = contents.match(tagword);
var type = 'smen';
var data = 'f=' +type+ '&menFriend=' +goname +'&posti='+ID;
if (goWord.length > 0) {
if (goname.length > 0) {
$.ajax({
type: "POST",
url: requestUrl + "searchuser",
data: data,
cache: false,
beforeSend: function() {
// Do Something
},
success: function(response) {
if(response){
$(".menlist"+ID).show().html(response);
}else{
$(".menlist"+ID).hide().empty();
}
}
});
}
}
}, 500);
});
Also here is a php section for searching user from database:
$searchmUser = mysqli_real_escape_string($this->db,$searchmUser);
$searchmUser=str_replace("#","",$searchmUser);
$searchmUser=str_replace(" ","%",$searchmUser);
$sql_res=mysqli_query($this->db,"SELECT
user_name, user_id
FROM users WHERE
(user_name like '%$searchmUser%'
or user_fullname like '%$searchmUser%') ORDER BY user_id LIMIT 5") or die(mysqli_error($this->db));
while($row=mysqli_fetch_array($sql_res,MYSQLI_ASSOC)) {
// Store the result into array
$data[]=$row;
}
if(!empty($data)) {
// Store the result into array
return $data;
}
Looks like you're sending an array which is result of match you in AJAX request.
Though I cannot test it but you can use a lookahead in your regex and use 1st element from resulting array. Negative lookahead (?!.*#\w) is used to make sure we match last element only.
var timer = null;
var tagword = /#(\w+)(?!.*#\w)/;
$("body").delegate(".addComment", "keyup", function(e) {
var value = e.target.value;
var ID = e.target.id;
clearTimeout(timer);
timer = setTimeout(function() {
var contents = value;
var type = 'smen';
var goname = contents.match(tagword);
if (goname != undefined) {
var data = 'f=' +type+ '&menFriend=' +goname[1] +'&posti='+ID;
$.ajax({
type: "POST",
url: requestUrl + "searchuser",
data: data,
cache: false,
beforeSend: function() {
// Do Something
},
success: function(response) {
if(response){
$(".menlist"+ID).show().html(response);
} else {
$(".menlist"+ID).hide().empty();
}
}
});
}
}, 500);
});

Cannot read property 'row' of undefined

//anything inside 'pagebeforecreate' will execute just before this page is rendered to the user's screen
$(document).on("pagebeforecreate", function () {
printheader(); //print the header first before the user sees his page
});
$(document).ready(function () {
searchfriend();
function searchfriend() {
var url = serverURL() + "/getcategories.php";
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getCategoryResult(arr);
},
error: function () {
validationMsg();
}
});
}
function _getCategoryResult(arr) {
var t; //declare variable t
//loop for the number of results found by getcategories.php
for (var i = 0; i < arr.length; i++) {
//add a new row
t.row.add([ //error
"<a href='#' class='ui-btn' id='btn" + arr[i].categoryID + "'>Category</a>" //add a new [Category] button
]).draw(false);
//We drew a [View] button. now bind it to some actions
$("#btn" + arr[i].categoryID).bind("click", { id: arr[i].categoryID }, function (event) {
var data = event.data;
showcategory(data.id); //when the user clicks on the [View] button, execute showcategory()
});
}
$("#categoryresult").show(); //show the results in the table searchresult
}
function showcategory(categoryID) {
//alert(categoryID);
window.location = "showuser.html?userid=" + userid;
}
});
There is an error on line 33 which stated:
"Uncaught TypeError: Cannot read property 'row' of undefined"
However, it seems that I have no idea where the error is coming from.
Is there anyway I can solve this problem?
You look like you are using a third-party jQuery plugin, DataTables.
Follow the usage of DataTables.
var t; //declare variable t
should be
var t = $("#categoryresult").DataTable();
The variable t is not an object with a property called row.
Try with var t = { row: [] }
Edit: I apologize. I got confused add with push method.
So, you need an object with a method called add and assign that object to t

Edit image src with jQuery

I have one question I'm using this code for editing image src's thats creating js but its not working ...(after click on button jquery creating object and then this function will change src's in this created object )
that code where first creating objects and second will edit image src's
function addToplaylist(title)
{
/* some CODE */
var each = playlistts.join('</span><li><img class="plimg" src="/img/cover.png"><span onclick="playinToplaylist($(this).html());" class="titletrack">');
$("#playlist").html('<li><img onload="this.src = \'/img/playlist/\'+$(this).next(\'span.titletrack\').text()+\'.jpg\'" src="/img/cover.png"><span onclick="playinToplaylist($(this).html());" class="titletrack">' + each);
/* some CODE */
}
$(document).ready(function(){
$("body .plimg").attr("src",
function (index) {
var title = $(this).next('span.titletrack').text();
var array = title.split(' - ');
var track = array[0];
var artist = array[1];
var output;
$.ajax({ //instead of getJSON as the function does not allow configurations.
url: "http://ws.audioscrobbler.com/2.0/?method=track.search",
data: {
track: track,
artist: artist,
api_key: "ca86a16ce762065a423e20381ccfcdf0",
format: "json",
lang: "en",
limit: 1
},
async: false, //making the call synchronous
dataType: 'json', //specifying JSON type
success: function (data) {
output = data.results.trackmatches.track.image[0]["#text"];
}
});
return output;
});
});

Speed Up Jquery heartbeats

I'm a pretty new programmer who made an application that sends out a heartbeat every 3 seconds to a php page and returns a value, the value of which decides which form elements to display. I've been fairly pleased with the results, but I'd like to have my jquery as fast and efficient as possible (its a little slow at the moment). I was pretty sure SO would already have some helpful answers on speeding up heartbeats, but I searched and couldn't find any.
So here's my code (just the jquery, but I can post the php and html if needed, as well as anything anyone needs to help):
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$('.jcontainer').each(function() {
var $e = $(this);
var dataid = $e.data("param").split('_')[1] ;
$.ajax({
url: 'heartbeat.php',
method: 'POST',
contentType: "application/json",
cache: true,
data: { "dataid": dataid },
success: function(data){
var msg = $.parseJSON(data);
if (msg == ""){ //after reset or after new patient that is untouched is added, show checkin
$e.find('.checkIn').show();
$e.find('.locationSelect').hide();
$e.find('.finished').hide();
$e.find('.reset').hide();
}
if ((msg < 999) && (msg > 0)){ // after hitting "Check In", Checkin button is hidden, and locationSelect is shown
$e.find('.checkIn').hide();
$e.find('.locationSelect').show();
$e.find('.finished').hide();
$e.find('.reset').hide();
$e.find('.locationSelect').val(msg);
}
if (msg == 1000){ //after hitting "Checkout", Option to reset is shown and "Finished!"
$e.find('.checkIn').hide();
$e.find('.locationSelect').hide();
$e.find('.finished').show();
$e.find('.reset').show();
}
}
});
});
},3000);
$('.checkIn').click(function() {
var $e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of button (1 for the first button)
// You can map this to the corresponding button in database...
$.ajax({
type: "POST",
url: "checkin.php",
// Data used to set the values in Database
data: { "checkIn" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.locationSelect').show();
$container.find('.locationSelect').val(1);
}
});
});
$('.reset').click(function() {
var $e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of button (1 for the first button)
// You can map this to the corresponding button in database...
$.ajax({
type: "POST",
url: "reset.php",
// Data used to set the values in Database
data: { "reset" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.checkIn').show();
}
});
});
$('.locationSelect').change(function(e) {
if($(this).children(":selected").val() === "CheckOut") {
$e = $(this);
var data = $e.data("param").split('_')[1] ;
$.ajax({
type: "POST",
url: "checkout.php",
// Data used to set the values in Database
data: { "checkOut" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.finished').show();
$container.find('reset').show();
}
});
}
else{
$e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of select (1 for the first select)
// You can map this to the corresponding select in database...
$.ajax({
type: "POST",
url: "changeloc.php",
data: { "locationSelect" : $(this).val(), "selectid" : data},
success: function() {
// Do something here
}
});
}
});
});
</script>
Thanks for all and any help! Please just ask if you need any more details! Thanks!
Alot of factors could be causing slowness. Some things to consider:
The speed of the heartbeat is not dependent on your client-side javascript code alone. There may be issues with your server-side php code.
Also, a heartbeat every three seconds is very frequent, perhaps too frequent. Check in your browser's developer debug tools that each of the requests is in fact returning a response before the next 3 second interval. It could be that your server is slow to respond and your requests are "banking up".
You could speed your your jQuery a fraction by streamlining your DOM manipulation, eg:
if (msg == "")
{
$e.find('.checkIn').show();
$e.find('.locationSelect, .finished, .reset').hide();
}

Please help optimize and write Jquery function that gets json data and appends it to select list options

Basically just need to write a jQuery/Ajax that fetches Json data (Price data) from server
and appends/overwrites each options text value so it would have the price difference between the
selected option and non selected option on the end of it. Only the non selected option should have the price difference showing on the end of it, see example below.
The code you will find below pretty much does this, but I can't seem to properly append/overwrite
it to the end of the option text value without the price difference being repeated (not replaced) onto the end with every onchange of the dropdown list. So I get [product name025252525] etc.
As well no idea how to not append the difference to the selected options text, I just get "0" there now as it minuses itself from itself.
The Json object (data) array is of the format {partid = 3, price = 234}, {partid = 6, price = 53} etc.
List should look like so:
[Intel i7 950] - selected visible option
[Intel i7 960 (+ $85)] - not selected but in the drop down list
[Intel i7 930 (- $55)] - not selected but in the drop down list
<script type="text/javascript">
$(document).ready(function () {
var arr = new Array();
$('select option').each(function () {
arr.push($(this).val());
});
$.ajax({
type: "POST",
url: "/Customise/GetPartPrice",
data: { arr: arr },
traditional: true,
success: function (data) { mydata = data; OnSuccess(data) },
dataType: "json"
});
});
$('select').change(function () { OnSuccess(mydata); });
function OnSuccess(data) {
$('select').each(function () {
var sov = parseInt($(this).find('option:selected').attr('value')) || 0; //Selected option value
var sop; //Selected Option Price
for (i = 0; i <= data.length; i++) {
if (data[i].partid == sov) {
sop = data[i].price;
break;
}
};
$(this).find('option').each(function () {
// $(this).append('<span></span>');
var uov = parseInt($(this).attr('value')) || 0; //Unselected option value
var uop; //Unselected Option Price
for (d = 0; d <= data.length; d++) {
if (data[d].partid == uov) {
uop = data[d].price;
break;
}
}
var newtext = uop - sop;
var xtext = $(this).text().toString();
$(this).attr("text", xtext + newtext);
// mob.append(newtext)
// $(this).next('span').html(newtext);
});
});
};
//$(document).ready(function () { $("#partIdAndCount_0__PartID").prepend('<option value="0">Select Processor<option>'); });
</script>
You are close:
$.ajax({
type: "POST",
url: "/Customise/GetPartPrice",
data: { arr: arr },
traditional: true,
success: OnSuccess,
dataType: "json"
});
OnSuccess is a function taking one parameter, data. So you simply use that method like above.
$('select').change(OnSuccess(data);); would compile if fixed like $('select').change(OnSuccess(data)); , minus the semicolon in the function. However, this is executing OnSuccess immediately. So again, $('select').change(OnSuccess); is what you want.
Declare a variable to store it in the outer scope:
var theJSON;
$(document).ready(function () {
var arr = new Array();
$('select option').each(function () {
arr.push($(this).val());
});
$.ajax({
type: "POST",
url: "/Customise/GetPartPrice",
data: { arr: arr },
traditional: true,
success: function (data) { theJSON = data; OnSuccess(theJSON)},
dataType: "json"
});
});
$('select').change(function(){ OnSuccess(theJSON); });

Categories

Resources