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');
...
Related
I am getting some data from an API using $.getJSON. I am appending the information to a div once I recieve it. But sometimes the data takes time to load and hence I want to display a loading functionality, until something is appended to the div. How do i do this?
function getApis(){
var source = document.getElementById('toplace').value;
var dest = document.getElementById('fromplace').value;
var options = "";
var container = document.getElementById('div-form');
var disp_info = document.getElementById('train-info');
// var train_block = document.getElementById("train-block");
container.style.display = 'none';
disp_info.style.display = 'inline-block';
var url = "http://api.railwayapi.com/between/source/" + source + "/dest/" + dest +"/date/18-09/apikey/abvsl2868/";
$.getJSON(url,function(data){
console.log(data);
// I WANT TO DISPLAY A LOADING FUNCTIONALITY UNTIL THIS DATA IS APPEARING ON THE SCREEN
$("#train-info").append("Total Number of trains running from " + source + " to " + dest + " : " + data.total + "<br><br><br>");
data.train.forEach(function(trains){
options = "<div style='border:1px solid black;font-family:'Kaushan Script''> <br>Train Name : " + trains.name + "<br><br>" +"Train Number : " + trains.number + "<br><br>Departure Time : " + trains.src_departure_time + "<br><br> Arrival Time : " + trains.dest_arrival_time + "<br><br></div>";
// $('#train-block').append(options + "<br>");
$('#train-info').append(options + "<br>");
});
});
}
You need to display your image, or whatever before the ajax call
$("#myDiv").html("<img src='spinner.gif'>");
$.ajax({
dataType: "json",
url: url,
data: data,
success: $("#myDiv").html("success");
});
Add a spinner image tag in the container element.
<div id="#train-info"><img src="loading-spinner.gif"/></div>
Before appending data to it, remove this image tag.
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.
I have a setInterval call inside my Javascript which checks if there are new notifications for the user. This interval makes an AJAX call and updates the DOM based on the response. This interval is set to repeat every 10 seconds.
There is a little box that needs to popup if there are new notifications and it is inside this interval. In the current code, this box shows up every 10 seconds if there are new notifications that are not marked as seen and that's pretty annoying.
Is there a way to make this little box appear only once per notification set? So for example there are X new notification and after 10 seconds this number didn't change, don't show this box. How do I achieve this? I'm stuck here.
This is how my interval code looks like:
setInterval(function(){
$.get(generate_site_url() + 'user.php?action=get_notifications', function(data) {
response = $.parseJSON(data);
if ('error' in response)
{
return;
}
if (response.notification_array.length == 0)
{
return;
}
$('.user-notification').text(response.notification_count);
$('.no-notes').hide();
var notificationStr = '';
for (var key in response.notification_array)
{
var notification = response.notification_array[key];
var notificationHTML = '<li' + ((notification.notification_seen == false) ? ' style="background: #fffaf1;"' : '') + '>';
notificationHTML += '<a href="' + notification.notification_target + '" id="nid-' + notification.notification_id + '">';
notificationHTML += '<span class="glyphicon glyphicon-' + ((notification.notification_type == 'like') ? 'thumbs-up' : (notification.notification_type == 'dislike') ? 'thumbs-down' : (notification.notification_type == 'favorite') ? 'heart' : 'bell') + '"></span> ';
notificationHTML += notification.notification_message;
notificationHTML += '</a></li>';
notificationStr += notification.notification_message + '<br />';
$('.notifications-dropdown').prepend($(notificationHTML));
}
display_alert(notificationStr, 'danger', 5000, 'bottom'); // This shows the box
});
}, 10000);
I'll expand my original comment answer here.
Set a variable accessible outside the interval function, in which you track the last count of new notifications. Next time the interval runs, compare the counts and check if there are any new ones.
var lastNewMessageCount = 0;
setInterval(function(){
// ajax stuff
if( response.notification_array.length > lastNewMessageCount ){
// show notices
}
lastNewMessageCount = response.notification_array.length;
});
Try making a global Array, then adding a conditional if(response.notification_array.length > nameOfGlobalArray.length) before the execution of display_alert() and update nameOfGlobalArray to match response.notification_array if the conditional returns true, like:
var notificationsArray = [];
setInterval(function(){
$.get(generate_site_url() + 'user.php?action=get_notifications', function(data) {
response = $.parseJSON(data);
if ('error' in response)
{
return;
}
if (response.notification_array.length == 0)
{
return;
}
$('.user-notification').text(response.notification_count);
$('.no-notes').hide();
var notificationStr = '';
for (var key in response.notification_array)
{
var notification = response.notification_array[key];
var notificationHTML = '<li' + ((notification.notification_seen == false) ? ' style="background: #fffaf1;"' : '') + '>';
notificationHTML += '<a href="' + notification.notification_target + '" id="nid-' + notification.notification_id + '">';
notificationHTML += '<span class="glyphicon glyphicon-' + ((notification.notification_type == 'like') ? 'thumbs-up' : (notification.notification_type == 'dislike') ? 'thumbs-down' : (notification.notification_type == 'favorite') ? 'heart' : 'bell') + '"></span> ';
notificationHTML += notification.notification_message;
notificationHTML += '</a></li>';
notificationStr += notification.notification_message + '<br />';
$('.notifications-dropdown').prepend($(notificationHTML));
}
if(response.notification_array.length > notificationsArray.length)
{
display_alert(notificationStr, 'danger', 5000, 'bottom');
notificationsArray = response.notification_array;
}
});
}, 10000);
[EDIT] BotskoNet's method uses less data, and apparently my brain wasn't turned on :P Both will work, though.
Does user.php mark a notification as seen once it has been delivered? I will assume not, but if so you just need to check if new notifications came in and only call the display_alert() if so.
Keeping track of notification count or comparing string is not enough. There are plenty of use cases where this will result in false positives. But I see there is a notification_id field:
var delivered= [];
setInterval(function(){
// ajax stuff
for (var key in response.notification_array){
var notification = response.notification_array[key];
// check if the notification has been delivered
if ($.inArray(notification.notification_id, delivered) === -1){
// notification has not been delivered
delivered.push(notification.notification_id);
// process notification as normal
}
}
// only display the alert if there is something to display...
if (notificationStr.length > 0)
display_alert(...);
}, 10000);
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.
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).