I want to set a div's text to "not found" in case the script fails to get the url in the script. I am using jQuery 1.4 version and I have to continue with it for some reason. Can anyone suggest some good ideas?
javascript
$(document).ready(function () {
$("#slides").html("");
$.get('someURl',
function (d) {
var i = 0;
var array = [];
var anchorImg = '';
$(d).find('entry').each(function () {
anchorImg = "<img id='imageID" + i + "' width='480' height='380'/>"
$("#slides").append(anchorImg);
var $entry = $(this);
var pic = $entry.find('content').attr('src');
array[i] = pic;
var ankita = "imageID" + i;
document.getElementById(ankita).src = array[i];
i++;
});
});
});
1.4 does not have deferred functions so your only option is to convert the $.get to a $.ajax call and use the error handler:
$.ajax({
method: 'GET',
url: 'someURl',
success: function(d) {
var i = 0;
var array = [];
var anchorImg = '';
$(d).find('entry').each(function() {
anchorImg= "<img id='imageID" + i + "' width='480' height='380'/>"
$("#slides").append(anchorImg);
var $entry = $(this);
var pic = $entry.find('content').attr('src');
array[i] = pic;
var ankita = "imageID" + i;
document.getElementById(ankita).src = array[i];
i++;
});
},
error: function() {
$('#slides').text('Not found');
}
});
You really should be pushing to use the latest version of jQuery though. 1.4 is nearly 4 years out of date!
Related
My variable tag returns one of these 4 different values: assistance, bug, evolution or maintenance. I would like to count how many times I have each of those words. I would like to display how many times I have each of those item in my console first. I really don't know how to do that. Here is my code :
function displaytickets(y){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/" + y + "/tickets/requested.json?per_page=150",
type: 'GET',
dataType: 'json',
cors: true ,
contentType: 'application/json',
secure: true,
beforeSend: function(xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function(data) {
var sortbydate = data.tickets.sort(function(a, b){
return new Date(b.created_at) - new Date(a.created_at);
});
var ids = $.map(data.tickets, function (data) {
return data.id;
})
localStorage.setItem("mesid", ids);
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
console.log(tag);
var myid = data.tickets[i].id;
}
var nbticket = data.tickets.length;
$("#name").append('<h2 class="title">' + " " + nbticket + " ticket(s)" + '</h2>');
},
});
}
Here's what I get from the console for the console.log(tag):
You can achieve this by using an object to store the occurrence count, keyed by the string itself. Try this:
var occurrences = {};
Then in your success handler you can add and increment the tags as you find them:
success: function(data) {
// your code here...
for (i = 0; i < data.tickets.length; i++) {
// your code here...
var tag = data.tickets[i].tags[0];
if (occurrences.hasOwnProperty(tag)) {
occurrences[tag]++;
} else {
occurrences[tag] = 1;
}
}
console.log(occurrences);
},
Working example
Did you try to count it in your for loop ?
var maintenance_counter = 0;
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
var myid = data.tickets[i].id;
if( tag == "maintenance" ){
maintenance_counter++;
}
}
alert("Total maintenance occurrence:"+ maintenance_counter);
Create an object to hold your tag result count, similar to this:
var tagCount = {};
for (i = 0; i < data.tickets.length; i++) {
var tag = data.tickets[i].tags[0];
if (tagCount[tag] === undefined) {
tagCount[tag] = 1;
} else {
tagCount[tag] += 1;
}
}
console.log(tagCount);
how do i display all content in my data array without repeating my self like i have done below .
// Program guide Rest
$(document).ready(function() {
$.ajax({
cache: false,
url: "http://engrid2media.com/nextt/api/epg/schedule/id/",
type: 'GET',
crossDomain: true,
dataType: 'json',
success: function() {
alert("EPG Success");
},
error: function() {
alert('EPG Failed!');
},
}).then(function(data) {
var result = data [0];
console.log(result);
$('.ch-name').append(result.ch_name);
$('.ch-logo').append(result.ch_logo);
$('.ch-desc').append(result.ch_desc);
$('.ch-genre').append(result.ch_genre);
$('.ch-type').append(result.type);
$('.ch-resolution').append(result.resolution);
var result1 = data [1];
console.log(result1);
$('.ch-name1').append(result1.ch_name);
$('.ch-logo1').append(result1.ch_logo);
$('.ch-desc1').append(result1.ch_desc);
$('.ch-genre1').append(result1.ch_genre);
$('.ch-type1').append(result1.type);
$('.ch-resolution1').append(result1.resolution);
var result2 = data [2];
console.log(result2);
$('.ch-name2').append(result2.ch_name);
$('.ch-logo2').append(result2.ch_logo);
$('.ch-desc2').append(result2.ch_desc);
$('.ch-genre2').append(result2.ch_genre);
$('.ch-type2').append(result2.type);
$('.ch-resolution2').append(result2.resolution);
var result3 = data [3];
console.log(result3);
$('.ch-name3').append(result3.ch_name);
$('.ch-logo3').append(result3.ch_logo);
$('.ch-desc3').append(result3.ch_desc);
$('.ch-genre3').append(result3.ch_genre);
$('.ch-type3').append(result3.type);
$('.ch-resolution3').append(result3.resolution);
var result4 = data [4];
console.log(result4);
$('.ch-name4').append(result4.ch_name);
$('.ch-logo4').append(result4.ch_logo);
$('.ch-desc4').append(result4.ch_desc);
$('.ch-genre4').append(result4.ch_genre);
$('.ch-type4').append(result4.type);
$('.ch-resolution4').append(result4.resolution);
var result5 = data [5];
console.log(result5);
$('.ch-name5').append(result5.ch_name);
$('.ch-logo5').append(result5.ch_logo);
$('.ch-desc5').append(result5.ch_desc);
$('.ch-genre5').append(result5.ch_genre);
$('.ch-type5').append(result5.type);
$('.ch-resolution5').append(result5.resolution);
});
});
This works fine , but it will be difficult to display over 20 items from the database with this method since i would have to do it one after the other.
A simple for loop would do it.
.then(function(data) {
for (var i = 0; i < 6; ++i)
{
var prefix = (i == 0 ? "" : i.toString());
$('.ch-name' + prefix).append(data[i].ch_name);
$('.ch-logo' + prefix).append(data[i].ch_logo);
$('.ch-desc' + prefix).append(data[i].ch_desc);
$('.ch-genre' + prefix).append(data[i].ch_genre);
$('.ch-type' + prefix).append(data[i].type);
$('.ch-resolution' + prefix).append(data[i].resolution);
}
});
Why not just write helper function?
Something like that.
function(data) {
var result,
suffix = '';
for (var i in data) {
result = data[i];
if (i > 0) {
suffix = i;
}
$('.ch-name' + suffix).append(result.ch_name);
$('.ch-logo' + suffix).append(result.ch_logo);
$('.ch-desc' + suffix).append(result.ch_desc);
$('.ch-genre' + suffix).append(result.ch_genre);
$('.ch-type' + suffix).append(result.type);
$('.ch-resolution' + suffix).append(result.resolution);
}
}
Try utilizing $.each()
$.each(data, function(key, val) {
var idx = key === 0 ? "" : key;
$(".ch-name" + idx).append(val.ch_name);
$(".ch-logo" + idx).append(val.ch_logo);
$(".ch-desc" + idx).append(val.ch_desc);
$(".ch-genre" + idx).append(val.ch_genre);
$(".ch-type"+ idx).append(val.type);
$(".ch-resolution" + idx).append(val.resolution);
});
I have been trying to learn how to write modules in JavaScript. With this attempt I am trying to load 10 pictures from Flickr on page load, and then load 10 more pictures once the user scrolls to the bottom of the page. This is not firing consistantly and I am not sure why.
I would like to load 10 pictures at page load, and then 10 additional pictures each time the user scrolls down to the bottom of the page.
I think the issue is with the curPage property that is called using this.settings.curPage
curPage is incremented in the jaxPhotos method using this.settings.curPage++
I am not sure but I think the issue is with either the jaxPhotos method or the scrollMorePics method.
Here's a fiddle with my module:http://jsfiddle.net/R3Bt7/
Here's my HTML:
<div class="flickrContainer" data-options='{"searchQuery" : "candy", "tagQuery" : "candy", "tagMode": "all", "picsPerPage" : "10", "curPage" : 1}'>
</div>
Here's my JS:
var FlickrModule = (function ($element) {
var flickrFeed = function () {
this.$element = $element;
this.init();
};
flickrFeed.prototype.init = function () {
this.setOptions()
.jaxPhotos(this.settings.curPage)
.onScrollHandler();
};
flickrFeed.prototype.setOptions = function () {
var options = this.$element.data().options;
var defaults = {
searchQuery : '',
tagQuery : '',
tagMode : '',
picsPerPage: '1',
curPage: 1
}
this.settings = $.extend({}, defaults, options);
return this;
};
flickrFeed.prototype.jaxPhotos = function (pageNumber) {
var self = this;
// ajax call to flickr json
$.ajax({
url: '//api.flickr.com/services/rest/?method=flickr.photos.search&api_key=xxxxxxxxxxxxxxxxxxxx&tags=' + this.settings.searchQuery + '&tag_mode=' + this.settings.tagMode + '&page=' + this.settings.currPage + '&per_page=' + this.settings.picsPerPage + '&format=json&jsoncallback=?',
dataType: 'jsonp',
data: JSON,
success: function (data) {
// start assembling some dom elements to wrap around each page
var pageTxtWrap = document.createElement('div'),
pageTxt= document.createElement('p');
pageTxt.textContent = 'Page ' + pageNumber + ' - Scroll down for more pictures!';
pageTxt.innerText = 'Page ' + pageNumber + ' - Scroll down for more pictures!';
pageTxtWrap.className = 'pageTextWrap';
pageTxtWrap.appendChild(pageTxt);
// Use createDocumentFragment() as it is the fastest method of element creation
var docFragPageHdr = document.createDocumentFragment();
docFragPageHdr.appendChild(pageTxtWrap);
document.body.appendChild(docFragPageHdr);
// create variables for easier access to the JSON trees we're using
flickr = data.photos,
flickrLength = flickr.photo.length;
// run through the JSON we just got and assemble the pictures
for (var i = 0; i < flickrLength; i++) {
var farmId = flickr.photo[i].farm,
serverId = flickr.photo[i].server,
photoId = flickr.photo[i].id,
secretId = flickr.photo[i].secret,
imgTitle = flickr.photo[i].title;
var flickImg = document.createElement('img');
flickImg.className = 'flickerImg';
flickImg.id = 'flickImg'+i;
flickImg.title = imgTitle;
flickImg.src = 'http://farm' + farmId + '.staticflickr.com/' + serverId + '/' + photoId + '_' + secretId + '_m.jpg';
var docFragFlickImg = document.createDocumentFragment();
docFragFlickImg.appendChild(flickImg);
document.body.appendChild(docFragFlickImg);
}
}
});
// increase currPage so we can go to the next page of pictures
this.settings.curPage++;
return this;
};
flickrFeed.prototype.onScrollHandler = function () {
$(document).on('scroll', this.scrollMorePics.bind(this));
return this;
};
flickrFeed.prototype.scrollMorePics = function(){
if ( $(window).scrollTop() + $(window).height() > $(document).height() - 50 ) {
console.log('Before ajax curPage = ', this.settings.curPage);
this.jaxPhotos(this.settings.curPage);
console.log('After ajax curPage = ', this.settings.curPage);
};
return this;
};
return flickrFeed;
}( $('.flickrContainer') ));
(function () {
var myModule = new FlickrModule();
})();
A small example on how you can access instance variables and methods based on your code:
var FlickrModule = (function ($) {
var flickrFeed = function ($element) {
this.$element = $element;
this.init();
};
flickrFeed.prototype.init = function(){
console.log('init', this.$element);
};
return flickrFeed;
})(jQuery);
$(function(){
var $container = $('.flickrContainer'),
fm = new FlickrModule($container);
});
http://jsfiddle.net/5nJqM/
Every time i try to use my classes below to post the array i made (also below) the ajax request doesn't pass the input as $_POST values but as $_REQUEST values seen in the web address bar at the top of the screen. I'm very new to Ajax and javascript (only been working with it about a month) so any tips and trick to fix anything below is greatly appreciated.
var formErrors=["Passage","FirstName","Zip"];
var formInput=["EventID","Passage","FirstName","LastName","Email","Organization","Location","Zip"];
Head of HTML
$(function () {
$("#signUp").click(function() {
if(formArrayValidation(formErrors) != false) {
formPostAjax(formInput, 'join-event.php');
}
return false;
});
});
Basics.js
formArrayValidation = function(errorArray) {
for(var i = 0; i < errorArray.length; i++) {
$('.error').hide();
var name = $("input#" + errorArray[i]).val();
if (name == "") {
$("label#" + errorArray[i] + "_error").show();
$("input#" + errorArray[i]).focus();
return false;
}
}
}
formPostAjax = function(inputArray, form) {
var dataString = "";
for(var i = 0; i < inputArray.length; i++)
{
var data = inputArray[i];
var dataInput = $("input#" + data).val();
if(i = 0) {
dataString = dataString + data + '=' + dataInput;
}
else {
dataString = dataString + '&' + data + '=' + dataInput;
}
}
$.ajax ({
type: "POST",
url: form,
data: dataString,
success: function() {
}
});
}
Your event listener should be on the form and it should be:
$('#form_identifier').submit(...);
Additionally, jQuery provides a nice shortcut method for serializing form data:
$('#form_identifier').submit(function(){
var post_data = $(this).serialize()
// ....
return false;
});
Is it possible to use like fuse.js with an XML document instead of JSON? As it is now I only have an XML document with data and hope that I shouldn't make a new version as well for JSON.
Hope someone can help me out which direction I can/should go.
Kind regards,
Niels
Found the solution myself. Instead of the example with JSON placed on http://kiro.me/projects/fuse.html, here is the version with an XML call instead :)
$(function() {
function start(books) {
var $inputSearch = $('#hero-search'),
$results = $('#results ul'),
$authorCheckbox = $('#value'),
$titleCheckbox = $('#typeId'),
$caseCheckbox = $('#case'),
searchAuthors = true,
searchTitles = false,
isCaseSensitive = false,
fuse;
function search() {
$results.empty();
$.each(r, function(i, val) {
$resultShops.append('<li class="result-item"><span><img src="' + this.statusId + '" /></span> ' + this.value + '</li>');
});
}
function createFuse() {
var keys = [];
if (searchAuthors) {
keys.push('value');
}
if (searchTitles) {
keys.push('typeId');
}
fuse = new Fuse(books, {
keys: keys,
caseSensitive: isCaseSensitive
});
}
$inputSearch.on('keyup', search);
createFuse();
}
$.ajax({
type: 'GET',
dataType: 'xml',
url: 'xml-document/document.xml',
success: function(response) {
var suggestions = [];
$(response).find("searchResults").children().each(function(i, elm) {
var name = $(elm).find('name').text();
var url = $(elm).find('url').text();
var description = $(elm).find('description').text();
var statusId = $(elm).find('status').text();
var typeId = $(elm).find('type').text();
var result = {};
result.value = name;
result.url = url;
result.description = description;
result.statusId = statusId;
result.typeId = typeId;
suggestions.push(result);
});
start(suggestions);
},
error: function(response) {
console.log('failure',response);
}
});
});