rendering list-images bbui from database mysql - javascript

I'm trying to make a list bbui image using ajax call in a mysql database, but in the process I do not get the same format as the image of bbui list, following my code
var idmember='glut1';
function dataOnLoad_initialLoad(element) {
var listItem, dataList = element.getElementById('dataList');
$.ajax({
type: "GET",
url: "ajax/history.php?id_member=" + idmember,
dataType: "json",
error: function(xhr, settings, exception) {
alert("error");
},
success: function(data){
$.each(data, function(key, val) {
listItem = document.createElement('div');
listItem.setAttribute('data-bb-type', 'item');
listItem.onclick = function() {
bb.pushScreen('detail.htm', 'detail');
};
listItem.setAttribute('data-bb-title', val.tglorder);
listItem.innerHTML = val.namastatus;
dataList.appendChild(listItem);
var order = val.idorder;
});
}
});
}
and then the code implemented in beforedetail.html like this code
<div id="dataList" data-bb-type="image-list" data-bb-images="none" data-bb-style="arrowlist">
</div>

I had a similar problem but my case was to generate an image list with a header to group items.
I did it the only way i know ho and it worked but am open to suggestions on how to do it better.
Here is the js code:
var listItem, header,
dataList = document.getElementById('dataList');// this is my list already in the DOM
var list = [];
var user = localDB.getScreenName();
$.ajax({
url: reg.api(),
data: {action: 'getAttire', formData: user},
type: 'post',
dataType: 'jsonp',
jsonp: false,
jsonpCallback: 'result',
beforeSend: function() {
document.getElementById('indicator').style.display = 'block';
},
complete: function() {
document.getElementById('indicator').style.display = 'none';
},
success: function(res) {
//showbList();
var title = [];
for (var i = 0; i < res.length; i++) {
if ($.inArray(res[i].item, title) === -1) {
title.push(res[i].item);//creates header array with unique values cos i had headers with duplicate names
}
// This creates header Array from the list
}
for (var k = 0; k < title.length; k++) {
header = document.createElement('div');
header.setAttribute('data-bb-type', 'header');
header.id = 'headers';
header.innerHTML = title[k];
header.style.background = '#f6f6f6';
header.style.fontSize = '20px';
header.style.fontWeight = 'bold';
// header.style.boxShadow = ''
list.push(header);//header created here
for (var i = 0; i < res.length; i++) {
if (header.innerHTML === 'Bag' && res[i].item === 'Bag') {
//var date =
listItem = document.createElement('div');
listItem.setAttribute('data-bb-type', 'item');
listItem.setAttribute('data-bb-img', res[i].img_link);
listItem.setAttribute('data-bb-title', res[i].name);
listItem.setAttribute('data-bb-accent-text', 'Added: '+jQuery.timeago(res[i].date));
listItem.setAttribute('dressup',res[i].DRESS_ID);
listItem.setAttribute('id','wardropeLink');
listItem.innerHTML = "Suited for: " + res[i].suited;
listItem.style.color = "#fff";
listItem.onclick = function() {
var selected = document.getElementById('wardropeLink').getTitle();
console.log(selected); // trying to get d title of a selected or clicked list but it returns the whole group. still working on it
};
list.push(listItem); //list item for a particular header created here
}
if (header.innerHTML === 'Trousers' && res[i].item === 'Trousers') {
listItem = document.createElement('div');
listItem.setAttribute('data-bb-type', 'item');
listItem.setAttribute('data-bb-img', res[i].img_link);
listItem.setAttribute('data-bb-title', res[i].name);
listItem.setAttribute('data-bb-accent-text', jQuery.timeago(res[i].date));
listItem.innerHTML = "Suited for: " + res[i].suited;
listItem.style.color = "#fff";
listItem.onclick = function() {
handleWardrope.listItems(res[i].DRESS_ID);
};
list.push(listItem);
}
}
}
var items = dataList.getItems();
if (items.length > 0) {
//list.insertItemBefore(item, items[0]);
} else {
dataList.refresh(list);//list added to DOM
if (bb.scroller) {
bb.scroller.refresh();
}
}
}
});
return false;
Hope this helps.
Warning and still trying to get the onclick function work for a particular list item but it seems to group them cos of the loop.

concerning the problem i had about getting the title of a list item
i solved it by calling the list selected function and then acted on the getTitle of the selected item.
code
listItem.onclick = function(){
var selected = document.getElementById('dataList').selected;
console.log(selected.getAttribute('dressup'));
}
what i did wrong before was i tried to get d selected item on d item itself and not on the imagelist.

Related

Onclick for arrays in JSON

I'm retrieving data through an api, and creating a list using JS. I was wondering if it was possible to create a onclick function for every element in an array element of a JSON. The elements are being displayed, but nothing happens when I click them. Also, is it possible to pass on data in the JSON with this redirection to a new page?
My code is as follows:
var url = "https://api.nytimes.com/svc/movies/v2/reviews/all.json?api-key=b5f6bc931d6e446a998eb063a7c13d8e";
$.ajax({
url: url,
method: 'GET',
dataType: 'json',
success: function (data) {
var data = data;
details(data);
for (var i = 0; i < Object.keys(data.results[0]).length; i++) {
document.getElementById("movlist");
var item = document.createElement('li');
item.className = 'listele';
var itempicdiv = document.createElement('div');
itempicdiv.className = 'picdiv';
var itempic = document.createElement('img');
itempic.className = 'pic';
itempic.src = data.results[i].multimedia.src;
var itemnamediv = document.createElement('div');
itemnamediv.className = 'namediv';
var itemname = document.createTextNode(data.results[i].display_title);
itemname.className = 'name';
itempicdiv.appendChild(itempic);
itemnamediv.appendChild(itemname);
item.appendChild(itempicdiv);
item.appendChild(itemnamediv);
list.appendChild(item);
}
}
}).done(function (result) {
console.log(result);
}).fail(function (err) {
throw err;
});
function details(data) {
for (var j = 0; j < Object.keys(data.results[0]).length; j++) {
var t = data.results[j];
t.onclick = function () {
location.href = 'detail.html';
}
}
}

Why does this function console.log 20 times instead of once?

In application.js, I have all the 'topics' compiling on the page from an ajax call, and then when one is clicked, all the information appears on the screen. Everything works great in development, but in production I get a 500 server error.
In trying to debug this, I noticed that the console is logging 20 times with the .onclick call. Why is this happening, and does it have any reason why it is returning a 500 error in production (heroku)?
I put ** ** around the 3 console.logs where this is happening.
if(window.location.pathname === "/topics") {
$('.actions').click(function(e) {
console.log("submit");
})
$.ajax({
url: '/topics',
dataType: 'json',
type: 'GET',
success: function(result) {
console.log(result);
for(var i = 0; i < result.length; i++) {
var title = result[i].title;
var level = result[i].level;
var id = result[i].id;
var favlink = '/topics/' + id + '/favorite';
var link = '/topics/' + id;
var topicInfo = {title: title, link: link};
var template = compiledTopics(topicInfo);
$('.topic-wrapper').append(template);
$('.listing-topics, .favorite-topic-title').click(function(e){
e.preventDefault();
if( $(this).hasClass("favorite-topic-title")) {
var heartClass = "favorited_heart_icon"
}
else if( $(this).hasClass("listing-topics")) {
var heartClass = "unfavorited_heart_icon";
$('html, body').animate({ scrollTop: 0 }, 'fast');
}
**console.log(this);**
$.ajax({
url: this,
dataType: "json",
type: 'GET',
success: function(result) {
var id = result.id;
var title = result.title;
var body = result.body;
var level = result.level
**console.log(level);**
//SHOW TOPIC and FAVTOPIC AS POPUP WHEN CLICKED
//Add proper favorite icon.
var favlink = '/topics/' + id + '/favorite';
**console.log(heartClass);**
var topicInfo = {title: title, body: body, heartClass: heartClass};
var template = compiled(topicInfo);
$('.topic-wrapper').append(template);
//CLOSE TOPIC WHEN CLICKING THE GREY SURROUNDING BOX - topicClose
$('.topicClose').click(function(e) {
$('.topicClose').css("display", "none");
$('.show_topic').css("display", "none");
})
//FAVORITE TOPIC
//ADD TO FAV TOPICS LIST
$(".unfavorited_heart_icon, .favorited_heart_icon").click(function(e) {
e.preventDefault();
//onclick - change colors of heart
if ( $(this).hasClass("favorited_heart_icon")) {
$(this).removeClass("favorited_heart_icon");
$(this).addClass("unfavorited_heart_icon");
urlEnd = '/unfavorite';
}
else if ( $(this). hasClass("unfavorited_heart_icon")) {
$(this).removeClass("unfavorited_heart_icon");
$(this).addClass("favorited_heart_icon");
urlEnd = '/favorite';
}
// console.log('/topics/favorite/' + id);
$.ajax({
url: '/topics/' + id + urlEnd,
type: 'POST',
success: function(result) {
location.reload();
}
})
});
},
error: function(err) {
console.log(err);
}
})
});
};
},
error: function(err) {
}
});
at the bottom of same js file:
var listingSource = $("#listingTopics").html();
var compiledTopics = Handlebars.compile(listingSource);
topics handlebar template:
<script id="listingTopics">
<div>
{{title}}
</div>
</script>
Thanks in advance!
EDIT**
I've also tried:
$.ajax({
url: '/topics',
dataType: 'json',
type: 'GET',
success: function(result) {
for(var i = 0; i < result.length; i++) {
var title = result[i].title;
var level = result[i].level;
var id = result[i].id;
var favlink = '/topics/' + id + '/favorite';
var link = '/topics/' + id;
var topicInfo = {title: title, link: link};
var template = compiledTopics(topicInfo);
$('.topic-wrapper').append(template).click(function(e) {
e.preventDefault();
console.log($(this))
});
};
},
I think a lot of the problems you are having with the assignment of multiple event listeners can be solved by taking those listeners out of the loops and defining them using the delegate strategy.
I would try something conceptually something similar to:
function getTopicJSON_Success(result){
console.log(result);
for(var i = 0; i < result.length; i++) {
var title = result[i].title;
var level = result[i].level;
var id = result[i].id;
var favlink = '/topics/' + id + '/favorite';
var link = '/topics/' + id;
var topicInfo = { title: title, link: link };
var template = compiledTopics(topicInfo);
$('.topic-wrapper').append(template);
}
}
function getJSON_Error(err){
console.log(err);
}
if(window.location.pathname === "/topics") {
$('.actions').click(function(e) {
console.log("submit");
});
$('.topic-wrapper').on("click", '.listing-topics, .favorite-topic-title', function(e){
e.preventDefault();
// =========================
// Note at this point "this" is the element that was clicked.
// in the ajax requrest below we will want to use $this.attr("href").
// =========================
console.log(this);
// =========================
var $this = $(this);
var heartClass;
if( $this.hasClass("favorite-topic-title") ) {
heartClass = "favorited_heart_icon"
} else if( $this.hasClass("listing-topics") ) {
heartClass = "unfavorited_heart_icon";
$("body").animate({ scrollTop: 0 }, 'fast');
}
// =========================
// Note: could be "null".
// Did you want one or the other specifically and not the posibility of null?
// =========================
console.log(heartClass);
// =========================
var getListJSON_Success = function(result){
var id = result.id;
var title = result.title;
var body = result.body;
var level = result.level
console.log(level);
//SHOW TOPIC and FAVTOPIC AS POPUP WHEN CLICKED
//Add proper favorite icon.
var favlink = '/topics/' + id + '/favorite';
var topicInfo = {title: title, body: body, heartClass: heartClass};
var template = compiled(topicInfo);
$('.topic-wrapper').append(template);
//CLOSE TOPIC WHEN CLICKING THE GREY SURROUNDING BOX - topicClose
$('.topicClose').click(function(e) {
$('.topicClose').css("display", "none");
$('.show_topic').css("display", "none");
});
//FAVORITE TOPIC
//ADD TO FAV TOPICS LIST
};
$.ajax({
url: $this.attr("href"),
dataType: "json",
type: 'GET',
success: getListJSON_Success,
error: getJSON_Error
})
});
$('.topic-wrapper').on("click", ".unfavorited_heart_icon, .favorited_heart_icon", function(e) {
e.preventDefault();
var $this = $(this);
var urlEnd;
if ( $this.hasClass("favorited_heart_icon") ) {
$this.removeClass("favorited_heart_icon");
$this.addClass("unfavorited_heart_icon");
urlEnd = '/unfavorite';
} else if ( $this. hasClass("unfavorited_heart_icon") ) {
$this.removeClass("unfavorited_heart_icon");
$this.addClass("favorited_heart_icon");
urlEnd = '/favorite';
}
$.ajax({
url: '/topics/' + $this.attr("id") + urlEnd,
type: 'POST',
success: function(result) { location.reload(); },
error: getJSON_Error
});
});
$.ajax({
url: '/topics',
dataType: 'json',
type: 'GET',
success: getTopicJSON_Success,
error: getJSON_Error
});
}
I'm guessing that results is roughly 20 items. When you're creating your click event handler within your for loop, your binding it to a classes .listing-topics, .favorite-topic-title. When you click on the element it goes ahead and fires the click events (20 times since you have 20 items in you results array). I suspect this is what is happening but need to see it to verify. Do you have a JSFiddle?
To fix this, change up the way you're binding your event handler. You need to scope it to a specific instance of a class or element in order for the events to fire individually instead of all at once.
SAMPLE SCENARIO
var results = ["1", "2", "3"];
//How you're currently doing it
for (var i = 0; i < results.length; i++) {
$('#container').append($('<div />', {text: results[i], class:'test-class'}));
$('.test-class').click(function () {
console.log($(this).text());
});
}
//Solution
for (var i = 0; i < results.length; i++) {
$('#container').append($('<div />', {text: results[i], class:'test-class'}).click(function () {
console.log($(this).text());
}));
}
I have created a simple reproduction of this scenario (aligning with yours) to help better explain what's happening. Basically, instaed of binding all your events within one go (by class), bind it to the element as you're creating it.
JSFIDDLE: https://jsfiddle.net/ncrxekmq/
UPDATED CODE
if(window.location.pathname === "/topics") {
$('.actions').click(function(e) {
console.log("submit");
})
$.ajax({
url: '/topics',
dataType: 'json',
type: 'GET',
success: function(result) {
console.log(result);
for(var i = 0; i < result.length; i++) {
var title = result[i].title;
var level = result[i].level;
var id = result[i].id;
var favlink = '/topics/' + id + '/favorite';
var link = '/topics/' + id;
var topicInfo = {title: title, link: link};
var template = compiledTopics(topicInfo);
$('.topic-wrapper').append(template);
//use $.each(index, item) to loop through all of your elements and bind the click event individually instead of in one go.
$('.listing-topics, .favorite-topic-title').each(function (index, item) {
$(item).click(function(e){
e.preventDefault();
if( $(this).hasClass("favorite-topic-title")) {
var heartClass = "favorited_heart_icon"
}
else if( $(this).hasClass("listing-topics")) {
var heartClass = "unfavorited_heart_icon";
$('html, body').animate({ scrollTop: 0 }, 'fast');
}
**console.log(this);**
$.ajax({
url: this,
dataType: "json",
type: 'GET',
success: function(result) {
var id = result.id;
var title = result.title;
var body = result.body;
var level = result.level
**console.log(level);**
//SHOW TOPIC and FAVTOPIC AS POPUP WHEN CLICKED
//Add proper favorite icon.
var favlink = '/topics/' + id + '/favorite';
**console.log(heartClass);**
var topicInfo = {title: title, body: body, heartClass: heartClass};
var template = compiled(topicInfo);
$('.topic-wrapper').append(template);
//CLOSE TOPIC WHEN CLICKING THE GREY SURROUNDING BOX - topicClose
$('.topicClose').click(function(e) {
$('.topicClose').css("display", "none");
$('.show_topic').css("display", "none");
})
//FAVORITE TOPIC
//ADD TO FAV TOPICS LIST
$(".unfavorited_heart_icon, .favorited_heart_icon").click(function(e) {
e.preventDefault();
//onclick - change colors of heart
if ( $(this).hasClass("favorited_heart_icon")) {
$(this).removeClass("favorited_heart_icon");
$(this).addClass("unfavorited_heart_icon");
urlEnd = '/unfavorite';
}
else if ( $(this). hasClass("unfavorited_heart_icon")) {
$(this).removeClass("unfavorited_heart_icon");
$(this).addClass("favorited_heart_icon");
urlEnd = '/favorite';
}
// console.log('/topics/favorite/' + id);
$.ajax({
url: '/topics/' + id + urlEnd,
type: 'POST',
success: function(result) {
location.reload();
}
})
});
},
error: function(err) {
console.log(err);
}
})
});
});
};
},
error: function(err) {
}
});

Count how many times i have the same word

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);

getting "undefined" when i print json array with js

I want to parse json array it came down from json.jsp, but when i access parse.js it displays undefined
Here is parse.js
$(document).ready(function() {
$('#login').click(function(event) {
$.get('json.jsp', {
}, function(responseText) {
var myJSONObject1 = responseText;
var myJSONObject = JSON.parse(myJSONObject1);
var len = myJSONObject.length;
var out = "";
for (var i = 0; i < len; i++) {
var student = myJSONObject[i];
out += "<li>"+student.ircEvent + "<li>" + student.method+"<li>"+student.regex;
}
document.getElementById("ajaxResponse").innerHTML = out;
});
});
});
and my json.jsp is,
<%
response.setContentType("plain/text");
User user = new User("RAM","ram#gmail.com");
User user1 = new User("Ravi","ravi#gmail.com");
User user2 = new User("Raghu","raghu#gmail.com");
List list = new ArrayList();
list.add(user);list.add(user1);list.add(user2);
String json = new Gson().toJson(list);
response.getWriter().write(json);
%>
when i access parse.js file, it displays undefined
any ideas......
Just use $.ajax and set the dataType to json. No need to parse anything. jQuery does it for you. http://api.jquery.com/jquery.ajax/
jQuery(document).ready(function($) {
$.ajax({
url: 'json.jsp',
type: 'get',
dataType: 'json',
success: function(data) {
if (data.length) {
var ajaxResponse = document.createElement('table'),
tbody = document.createElement('tbody');
for (var i in data) {
if (data.hasOwnProperty(i)) {
var tr = document.createElement('tr'),
key = document.createElement('td'),
keyText = document.createTextNode(i),
value = document.createElement('td'),
valueText = document.createTextNode(data[i]);
key.appendChild(keyText);
tr.appendChild(key);
value.appendChild(valueText);
tr.appendChild(value);
tbody.appendChild(tr);
}
}
ajaxResponse.appendChild(tbody);
$("#ajaxResponse").append(ajaxResponse);
}
else alert("No data returned!");
}
});
});

How to add data asp:dropdownlist item on javascript?

I have ajax function on aspx page.
function fav() {
var p = "3";
var e = document.getElementById('<%= ddlCountry.ClientID %>');
var j = e.options[e.selectedIndex].text;
//var aralik = p[1] + p[2];
$.ajax({
type: "POST",
url: "STry.aspx/Fill",
data: "{'Param': '" + p + "','Param2': '" + j + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, error) {
//alert the error if needed
},
success: function (msg) {
var data = msg.d;
if (data.indexOf(',') < 0)
{
document.getElementById('<%= ddlCity.ClientID %>').options.add(data);
}
else
{
data.split(",").forEach(function (item) {
var opt = document.createElement(item);
document.getElementById('<%= ddlCity.ClientID %>').options.add(opt);
});
}
}
});
}
the data return var data = msg.d; so, my return data is data. data type like this, if one more than;
text1,text2,text3,text4
and i want to split this value and add dropdownlist that is ddlCity
this part is my try:
var data = msg.d;
if (data.indexOf(',') < 0)
{
document.getElementById('<%= ddlCity.ClientID %>').options.add(data);
}
else
{
data.split(",").forEach(function (item) {
var opt = document.createElement(item);
document.getElementById('<%= ddlCity.ClientID %>').options.add(opt);
});
but it is not working.
Briefly, I have a return data like (text1,text2,text3,text4) how to add return data in ddlCity item on javascript?
Thank you for your answers.
Try this
data.split(",").forEach(function (item) {
var option = document.createElement("option");
option.text = item;
option.value = item;
var ddl= document.getElementById('<%= ddlCity.ClientID %>')
ddl.appendChild(option);
});
Check below
append option to select menu?
Using forEach as in your code snippet:
Demo: http://jsfiddle.net/abhitalks/63eX6/1/
var data = "text1,text2,text3,text4";
var ddl = document.createElement("select");
ddl.id = "s1";
document.getElementById("container").appendChild(ddl);
data.split(",").forEach(function(item) {
var opt = document.createElement("option");
opt.value = item;
opt.text = item;
ddl.appendChild(opt);
});
Create a select, assign an id to it, and append it to an existing container like div,
Loop over the split array, create option element, assign value and text and then append it to the select.

Categories

Resources