pagination with AJAX url - javascript

Im beginner in AJAX & JS so please bear with me.
I use this AJAX for the pagination :
$(function () {
var keyword = window.localStorage.getItem("keyword");
//pagination
var limit = 3;
var page = 0;
var offset = 0;
$("#btnLoad").on('click', function () {
page++;
if (page != 0)
offset = (page - 1) * limit;
$.ajax({
url: "http://localhost/jwmws/index.php/jwm/search/msmall/" + keyword + "/" + limit + "/" + offset, //This is the current doc
type: "GET",
error: function (jq, st, err) {
alert(st + " : " + err);
},
success: function (result) {
alert("offset=" + offset + " page =" + page);
//generate search result
$('#search').append('<p style="float:left;">Search for : ' + keyword + '</p>' + '<br/>' + '<p>Found ' + result.length + ' results</p>');
if (result.length == 0) {
//temp
alert("not found");
} else {
for (var i = 0; i < result.length; i++) {
//generate <li>
$('#list').append('<li class="box"><img class="picture" src="images/HotPromo/tagPhoto1.png"/><p class="name"><b>Name</b></p><p class="address">Address</p><p class="hidden"></p></li>');
}
var i = 0;
$(".box").each(function () {
var name, address, picture, id = "";
if (i < result.length) {
name = result[i].name;
address = result[i].address;
picture = result[i].boxpicture;
id = result[i].mallid;
}
$(this).find(".name").html(name);
$(this).find(".address").html(address);
$(this).find(".picture").attr("src", picture);
$(this).find(".hidden").html(id);
i++;
});
$(".box").click(function () {
//alert($('.hidden', this).html());
window.localStorage.setItem("id", $('.hidden', this).html());
$("#pagePort").load("pages/MallDetail.html", function () {});
});
}
}
});
}).trigger('click');
});
Please notice that i use the variables for pagination in the url:. I tried to alert the page and offset variable, and its working fine.
However, the AJAX only working for the first page (when page load). The rest is not working even though the page and offset variable's value is true.
Theres no warning/error in console. The data just not shown.
Any help is appreciated, Thanks :D

It is a bit hard to debug your code when the whole HTML is missing.
Could you put your code into JSFiddle, both HTML and JS.

Related

Strange javascript (jQuery) behaviour

I have simple chat that uses ajax to get messages, heres the code:
function get_message_chat() {
$.ajaxSetup({
url: "chat.php",
global: true,
type: "GET",
data: "event=get&id=" + mid + "&t=" + (new Date).getTime()
});
$.ajax({
success: function(msg_j) {
if (msg_j.length > 2) {
var obj = JSON.parse(msg_j);
for (var i = 0; i < obj.length; i++) {
console.log(msg_j.length);
if (mid >= obj[i].id) {
continue;
}
mid = obj[i].id;
name = obj[i].name;
msg = obj[i].msg
$("#msg-box ul").append("<li><b><span class=\"username\" >" + name + "</span></b>:<span id=\"msgid_" + mid + "\" class=\"messsage\" style=\"color:black;\" > " + msg + "</span></li>");
if (msg.indexOf('#' + username) != -1) {
$("#msgid_" + mid).css('font-weight', 'bold');
}
}
$("#msg-box").scrollTop(2000);
}
}
});
setTimeout(get_message_chat, 2000);
}
mid = 0;
It grabs messages from php script "starts from mid ID". Then it shows messages to chat(appends to ul) and sets mid to new message id and then loop repeats. The problem is that it stucks fter mid = 9 for some reason. I still have more messages coming:
[{"id":"10","name":"user1","msg":"messages1234"},
{"id":"11","name":"user2","msg":"messages5678"}]
But they wont display. Everyting looks fine, but I can't understand why is that happening. Thank you for all comments.

Refreshing / Cycling through a parsed RSS feed every 5 mins

I am working on a monitor signage display and have a "welcome to RSS" feed with just a title and desc. I have code from feedEk that's been tweaked a bit to parse the feed and cycle it so I only have one title and desc. showing at a time. This feed could be added to or deleted info at any time so I need it to refresh every five mins. I've tried several solutions on here and just can't seem to work it out.
Here is the adjusted FeedEk code with comments on the adjustments:
(function (e) {
e.fn.FeedEk = function (t) {
var n = {
FeedUrl: "http://myrss.com/",
MaxCount: 1,
ShowDesc: true,
ShowPubDate: false,
CharacterLimit: 100,
TitleLinkTarget: "_self",
iterate: false
};
if (t) {
e.extend(n, t)
}
var r = e(this).attr("id");
var i;
processFeedData = function (t) {
//This just makes it flash too much
//e("#" + r).empty();
var s = "";
en = t.responseData.feed.entries;
if (n.iterate == true) {
//Setting a variable to store current item
i = window.feedcur = typeof(window.feedcur) === 'undefined' ? 0 : window.feedcur;
t = en[i];
s = makeString(t);
//incrementing the current for the next time we loop through
window.feedcur = ((i+1)%en.length);
} else {
for (i=0;i<en.length;i++) {
t = en[i];
s += makeString(t);
}
}
//Changing this to just replace what was there (less blinky feeling)
e("#" + r).html('<ul class="feedEkListSm">' + s + "</ul>");
}
makeString = function (t) {
s = '<li><div class="itemTitleSm"><a href="' + t.link + '" target="' + n.TitleLinkTarget + '" >' + t.title + "</a></div><br>";
if (n.ShowPubDate) {
i = new Date(t.publishedDate);
s += '<div class="itemDateSm">' + i.toLocaleDateString() + "</div>"
}
if (n.ShowDesc) {
if (n.DescCharacterLimit > 0 && t.content.length > n.DescCharacterLimit) {
s += '<div class="itemContentSm">' + t.content.substr(0, n.DescCharacterLimit) + "...</div>"
} else {
s += '<div class="itemContentSm">' + t.content + "</div>"
}
}
return s;
}
if (typeof(window.feedContent) === 'undefined') {
e("#" + r).empty().append('<div style="padding:3px;"><img src="loader.gif" /></div>');
e.ajax({
url: "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=" + n.MaxCount + "&output=json&q=" + encodeURIComponent(n.FeedUrl) + "&hl=en&callback=?",
dataType: "json",
success: function (t) {
window.feedContent = t;
processFeedData(window.feedContent);
}
});
} else {
processFeedData(window.feedContent);
}
}
})(jQuery)
On the php page I have the following code which cycles through on an interval. I've tried wrapping this into another function that refreshes it but that didn't work. I've also tried just refreshing the page, but that just makes the whole page blink and still doesn't refresh the feed. It seems to refresh every 12 to 24 hours.
<!-- this is for the rss feed -->
<script type="text/javascript" >
$(document).ready(function () {
feedsettings = {
FeedUrl: 'http://myrss.com/',
MaxCount: 100,
ShowDesc: true,
ShowPubDate: false,
DescCharacterLimit: 100,
iterate: true
}
$('#divRss').FeedEk(feedsettings);
setInterval(function(){
$('#divRss').FeedEk(feedsettings);
},7000);
});
</script>
<style>
.rssDiv{float:right; padding-left:35px;}
ul{width:500px !important}
</style>
<!-- end feed stuffs -->
Any help guidance assistance or direction is immensely appreciated. I have to make this self sustaining with little to no extra installations. I've also posted this on code review but I think that may have been the wrong place to post this initially.

Parsing the json data from google and twitter differences

I am new to javascript. I have worked on twitter API. In twitter API i used jQuery.ajax function to get json data from twitter servers. But when i use the same option with google maps server, my app isn't giving any response the moment it enters the jQuery.ajax. I tried to debug it using jslint, but it came out clean. I used debugging using alert, and it stops when it enters jQuery.ajax function. Is meathod to retrieve data varies with the source ?
If not why isn't my code responding ?
Twitter running function ::
var twitterapi = "http://search.twitter.com/search.json?";
jQuery.ajax(
{
type: "GET",
url: twitterapi,
data:
{
"q": hashtag,
"rpp": 1000
},
dataType: 'jsonp'
}).done(function (response)
{
var results = response.results;
for (var i = 0; i < results.length; i++)
{
$("#tweet").prepend("<li class='tweet'>" +
"<img src='" +
results[i].profile_image_url +
"'/>" +
"<span class='username'>" +
results[i].from_user +
"</span> <span class='tweet_content'> " +
results[i].text +
"</span></li>");
}
});
My google maps API(not working)
var j = 2;
var friends = [];
var distance =[];
$(document).ready(function () {
alert("function started");
$('#button').click(function () {
if (j < 11) {
$('#friends').append('Friend' + j + ':<input type="text" id="friend' + j + '"/><br/><br/>');
j++;
}
else {
alert("Limit reached");
}
});
$('button').click(function(){
var a =[];
alert("button clickede");
for(i=1;i<=j;i++)
{
a[i] = $("#friend" + i).val();
}
var gurl = "http://maps.googleapis.com/maps/api/distancematrix/json?"+
"origins=" +
a.join('|').replace(/ /g,'+') +
"&destinations=" +
a.join('|').replace(/ /g,'+') +
"&sensor=false";
alert("making request to" +gurl);
jQuery.ajax(
{
type: "GET",
url: gurl,
dataType: 'jsonp'
}).done(function (response)
{
alert("request made to"+gurl);
var rows = response.rows;
alert(row[0].elements[0].value);
for(var i=0;i<rows.length;i++)
{
for(var j=0;j<elements.length;j++)
{
distance[i][j] = row[i].elements[j].distance.value;
}
}
alert(distance[0][0]);
});
});
});
I don't know what error are you getting so i can't be of much help.
But the code you posted has three issues:
1- Since a is undefined, i couldn't get past the first two lines.
2- Removing the a calls in the code, then it threw a Syntax Error. I fixed this by removing the last }); line.
3- It made the request, but it threw another error (probably because the URL was malformed).

IE not loading XML content until I open Developer tools?

I have a page that loads product information from an XML file using a jQuery AJAX get request. This works well in FF and Chrome however the content doesn't load in IE. It will however load the data after opening the developer window and refreshing the page! Does anyone know why?
Here is my jQuery AJAX request:
//Load the xml file
$.ajax({
type: "GET",
url: "xml/" + cat + ".xml",
dataType: ($.browser.msie) ? "text" : "xml",
success: function(data) {
alert('xml successfully loaded');
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
//Get total number of products in the category
$(xml).find('dataroot').each(function() {
var pTemp = $(this).attr('count');
catName = $(this).attr('catTitle');
console.log(catName);
pTotal = Number(pTemp);
});
//Fill the correct entries onto the page
while (count<=pTotal) {
$(xml).find('product').each(function() {
if (count>lCounter && count<hCounter) {
var pName = $(this).find('ProductName').text();
var pImage = $(this).find('Photo').text();
var pCode = $(this).find('ProductCode').text();
var pDesc = $(this).find('WebDescription').text();
if (cat.substring(0,2)=='cs') {
var pPrice = $(this).find('PartyShackPrice').text();
} else { var pPrice = $(this).find('RRP').text(); }
var pSize = $(this).find('size').text();
var pLink = '<a href="item.html?'+cat+'-'+pCode+'">';
var pHTML = '<div id="'+pCode+'" class="box">';
pHTML += pLink + '<img src="images/SMALL_IMAGE/' + pImage + '" width="70" height"100" /></a>';
pHTML += '<div class="boxText">';
pHTML += pLink + '<div class="boxTitle">'+pName+'</div></a>';
pHTML += '<div class="boxDesc">'+pDesc+'</div>';
if (pSize !== 'Not Applicable') { pHTML += '<div class="boxSize">'+pSize+'</div>'; }
pHTML += '<div class="boxPrice">£'+pPrice+'</div>';
pHTML += pLink + '<div class="boxBuy"></div></a>';
pHTML += '</div></div>';
$("#products").append(pHTML);
}
count +=1;
});
}
//Work out the total number of pages the product list is split up into
if (pTotal%50==0) { pageTotal = pTotal/50; }
else { pageTotal = Math.floor(pTotal/50) + 1; }
console.log('pageTotal - ' + pageTotal);
//Show path of the current page
getPath(cat, catName, 0);
//Depending on page number show previous and next buttons and display product counter
if (pageTotal==1) { //page 1 and only one page
$("#prev").css("visibility", "hidden");
$("#next").css("visibility", "hidden");
$("#counter").append('1 - ' + pTotal + ' of ' + pTotal);
} else if ((pageNum==1) && (pageTotal!=1)) { //page 1 and multiple pages
$("#prev").css("visibility", "hidden");
$("#next").append('Next >>');
$("#counter").append('1 - 50 of ' + pTotal);
} else if ((pageNum==pageTotal) && (pageTotal!=1)) { //last page when theres more than 1 page
$("#next").css("visibility", "hidden");
$("#prev").append('<< Previous');
$("#counter").append((((pageNum-1)*50)+1) + ' - ' + pTotal + ' of ' + pTotal);
} else { // a middle page
$("#next").append('Next >>');
$("#prev").append('<< Previous');
$("#counter").append((((pageNum-1)*50)+1) + ' - ' + (pageNum * 50) + ' of ' + pTotal);
}
//Display page number
$("#currentPage").append(' ' + pageNum + ' of ' + pageTotal);
},
error: function() { alert('failure'); }
});
});
Also IE should call either the success alert or the error alert however it does neither until opening the developer window and refreshing the page.
Thanks
I knew what the problem was just by reading the title of your question on the SO main page. And reading the code in the question confirms it. The problem you have is the line console.log(catName);
IE (and some other browsers) don't initialise the console object until the developer window is opened.
Prior to this, trying to use console will return undefined, and will cause your script to stop running.
The first lesson here is not to leave debugging code in your program after you're done with it. Calls to the console should only be there while you're testing the program; when you've finished with them, take them out.
The second lesson is that if you do need to have console calls in your code, you should wrap them in code that checks if console exists before it tries to use it. There are a number of ways to do this, from a simple if(console) {console.log(...);} all the way through to writing your own debugging class. How you do it is up to you, but it is generally a good idea to write all console code this way, even when you're just doing a bit of debugging, to avoid the kind of issue you're having here.
Hope that helps.
Let jQuery do what it does best. Replace all of this:
dataType: ($.browser.msie) ? "text" : "xml",
success: function(data) {
alert('xml successfully loaded');
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
...
With this:
dataType: "xml",
success: function(xml) {
alert('xml successfully loaded');
...

retrieving the twitter search feeds dynamically using ajax

Long back I used JSON and was successful to get the hash tag feeds from twitter and facebook. But presently I am just able to get the feeds but its not being updated constantly that means it not been update dynamically. I guess I need to ajaxify it, but I am not able to do that since I am not aware of ajax. Here is the code which I have used to get the twitter search feeds.
$(document).ready(function()
{
$("#Enter").click(function(event){
var searchTerm = $("#search").val() ;
var baseUrl = "http://search.twitter.com/search.json?q=%23";
$.getJSON(baseUrl + searchTerm + "&rpp=1500&callback=?", function(data)
{
$("#tweets").empty();
if(data.results.length < 1)
$('#tweets').html("No results JOINEVENTUS");
$.each(data.results, function()
{
$('<div align="justify"></div>')
.hide()
.append('<hr> <img src="' + this.profile_image_url + '" width="40px" /> ')
.append('<span><a href="http://www.twitter.com/'
+ this.from_user + '">' + this.from_user
+ '</a> ' + makeLink(this.text) + '</span>')
.appendTo('#tweets')
.fadeIn(800);
});
});
});
});
function makeLink(text)
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
The code below should help you. What I've done is moved the code which fetches the tweets into a function. This function is then called every X seconds to update the box. When the user enters a new search term and clicks "Enter", it will reset the timer.
var fetchSeconds = 30; //Number of seconds between each update
var timeout; //The variable which holds the timeout
$(document).ready(function() {
$("#Enter").click(function(event){
//Clear old timeout
clearTimeout(timeout);
//Fetch initial tweets
fetchTweets();
});
});
function fetchTweets() {
//Setup to fetch every X seconds
timeout = setTimeout('fetchTweets()',(fetchSeconds * 1000));
var searchTerm = $("#search").val();
var baseUrl = "http://search.twitter.com/search.json?q=%23";
$.getJSON(baseUrl + searchTerm + "&rpp=1500&callback=?", function(data) {
$("#tweets").empty();
if (data.results.length < 1) {
$('#tweets').html("No results JOINEVENTUS");
}
$.each(data.results, function() {
$('<div align="justify"></div>').hide()
.append('<hr> <img src="' + this.profile_image_url + '" width="40px" /> ')
.append('<span>' + this.from_user + ' ' + makeLink(this.text) + '</span>')
.appendTo('#tweets')
.fadeIn(800);
});
});
}
function makeLink(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
Hope this helps

Categories