I'm making site in which I have to add some element but only when they contain class .addEvent but when I try document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent")
It shows me this error in console (json[i].date is something like: 2019-11-06):
TypeError: document.getElementsByClassName(...).classList is undefined
And when I display date in console it shows as it should be.
Here is my whole javascript code, maybe it would help:
$(() => {
var event;
$.ajax({
type: "GET",
url: "getEvents.php",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function(json) {
for (var i = 0; i < json.length; i++) {
console.log(document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent"));
if (document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent")) {
document.getElementsByClassName(json[i].date)[0].innerHTML += " <br/><span class='event'>" + json[i].name + "<br/>" + json[i].place + "</span>";
document.getElementsByClassName(json[i].date)[0].style.backgroundColor = json[i].color;
document.getElementsByClassName(json[i].date)[0].style.color = "#ffffff";
document.getElementsByClassName(json[i].date)[0].style.fontWeight = "bold";
document.getElementsByClassName(json[i].date)[0].style.opacity = "0.6";
}
}
},
error: function(error) {
alert("error");
console.log(error);
}
});
var day;
var shown = false;
$("td.addEvent").click(function() {
if (shown == false) {
$(".addEventMenu").css("display", "block");
day = getDay($(this));
var clickedDay = document.getElementsByTagName("p");
clickedDay[1].innerHTML += day;
shown = true;
}
});
function getDay(input) {
return input.clone().children().remove().end().text();
}
$("button.addEventBtn").click(function(e) {
e.preventDefault();
var year;
var month = $(".month").val();
const regex = /[0-9]{4}/gm;
let m;
while ((m = regex.exec($(".date").text())) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
year = `${match}`;
});
}
var name = $(".eventName").val();
var description = $(".eventDescription").val();
var place = $(".eventPlace").val();
var startHour = $('.eventStartHour').val();
var endHour = $('.eventEndHour').val();
var color = $('.eventColor').val();
var userId = $('input.userId').val();
if (day < 10) {
day = "0" + day;
}
var date = year + "-" + month + "-" + day;
$.ajax({
url: 'addEvent.php',
data: {
'eventName': name,
'eventDescription': description,
'eventPlace': place,
'eventStartHour': startHour,
'eventEndHour': endHour,
'eventColor': color,
'eventDate': date,
'userId': userId
},
type: 'post',
success: function(data) {
},
error: function(request, status, error) {
alert(request, status);
}
});
});
$("p.closeEventMenu").click(function() {
$(".addEventMenu").css("display", "none");
var clickedDateDay = $("p.clickedDay").text();
clickedDateDay = clickedDateDay.replace(/\s+$/, '');
$("p.clickedDay").text(clickedDateDay.substring(0, clickedDateDay.length - 2));
shown = false;
});
});
You are not confirming that the element exists before trying to use it.
if (document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent"))
If no elements matching class json[i].date exist, this if will throw the exception.
You should confirm the selector is returning elements before trying to use any of them:
var elements = document.getElementsByClassName(json[i].date);
if(elements.length > 0 && elements[0].classList.contains("addEvent"))
This will confirm the element actually exists before attempting to gather any information (classList) from the element. Of course, whether or not the element exists depends on many other factors - but in this case it seems that there are not any elements matching the selector on the page.
Related
I want to display data stored in ch ! But my problem is that ch is displayed before the data is stored !
I think this is an Asynchronous Problems! How can I solve this problem.
When I try to get length of ch, I get always 0. Even if I store data statically in ch, I get the length 0.
I think this is an Asynchronous Problems! How can I solve this problem.
function RechercheFiltrée() {
var nom = document.getElementById('nompre').value;
var matricule = document.getElementById('matcle').value;
$.ajax({
url: "myWebServiceURL",
type: "GET",
dataType: "xml",
success: function(xml) {
var stock = [];
$(xml).find('Population').each(function() {
var table = document.getElementById("myTable");
$(this).find("directories").each(function()
{
dossier = $(this).attr('dossier');
stock.push(dossier);
});
});
var ch = [];
for (var i = 0; i < stock.length; i++) {
$.ajax({
url: "/mySecondWebServiceURL" + stock[i],
type: "GET",
dataType: "xml",
success: function(xml) {
var NMPRES = "";
var jsonObj = JSON.parse(xml2json(xml, ""));
var nom = jsonObj.SubmitResponse.occurrences.occurrence.filter(x => x["#datasection"] === "TS")[0].data.filter(x => x.item === "NMPRES")[0].value;
var matcle = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0].data.filter(x => x.item === "MATCLE")[0].value;
var dossier = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0]["#dossier"];
ch.push({
"nom": nom,
"matcle": matcle,
"dossier": dossier
});
if ($('#population').val() != null && firstIter == false) {
}
},
error: function(request, error) {
console.log('error Connexion : ' + error + ' request Connexion : ' + request);
}
});
}
var txt = "";
var firstIter = true;
for (var key in ch) {
if (ch[key].matcle === matricule) {
txt += "<option value='" + ch[key].dossier + "'" + firstSelect(firstIter) + ">" + ch[key].nom + "</option>";
firstIter = false;
}
}
$('#population').html(txt)
},
error: function(request, error) {
console.log('error Connexion : ' + error + ' request Connexion : ' + request);
}
});
}
The problem is that you are not waiting for the second service to respond.
It should be something like this:
const deferreds = stock.map((stockItem) => {
//... your logic with ch.push here
return $.ajax({
// your call to the second service
});
});
$.when(...deferreds).then(() => {
// your code
// for (var key in ch) {
});
The approach I'd rather take is to break the code down and use Promises. You really should take your time to learn Promises. It's a JavaScript standard and what jQuery uses under the hood.
function RechercheFiltrée() {
var nom = document.getElementById('nompre').value;
var matricule = document.getElementById('matcle').value;
return $.ajax({
url: "myWebServiceURL",
type: "GET",
dataType: "xml"
});
}
function getStockArray(xml) {
var stocks = [];
$(xml).find('Population').each(function() {
var table = document.getElementById("myTable");
$(this).find("directories").each(function() {
{
dossier = $(this).attr('dossier');
stocks.push(dossier);
});
});
});
return stocks;
}
function getStocks(stocks) {
return Promise.all(stocks.map(fetchStock));
}
function fetchStock (stock) {
return $.ajax({
url: "/mySecondWebServiceURL" + stock,
type: "GET",
dataType: "xml"
})
.then(formatStockInfo)
}
function formatStockInfo (xml) {
var NMPRES = "";
var jsonObj = JSON.parse(xml2json(xml, ""));
var nom = jsonObj.SubmitResponse.occurrences.occurrence.filter(x => x["#datasection"] === "TS")[0].data.filter(x => x.item === "NMPRES")[0].value;
var matcle = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0].data.filter(x => x.item === "MATCLE")[0].value;
var dossier = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0]["#dossier"];
if ($('#population').val() != null && firstIter == false) {
}
return {
"nom": nom,
"matcle": matcle,
"dossier": dossier
};
}
function updateSelectMenu (ch) {
var txt = "";
var firstIter = true;
for (var key in ch) {
if (ch[key].matcle === matricule) {
txt += "<option value='" + ch[key].dossier + "'" + firstSelect(firstIter) + ">" + ch[key].nom + "</option>";
firstIter = false;
}
}
$('#population').html(txt)
}
RechercheFiltrée()
.then(getStockArray)
.then(getStocks)
.done(updateSelectMenu);
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);
function GetViewModelData() {
var RDcViewModel = [];
var recordId = $.trim($("#recordId").val());
for (i = 1; i <= rowCount; i++) {
var item1 = $.trim($("#item1" + i).val()) == '' ? 0 : parseInt($("#item1" + i).val());
var item2 = $.trim($("#item2" + i).val()) == '' ? 0 : parseInt($("#item2" + i).val());
var GrandTotal = (item1 + item2);
var rdtCViewModel = new ItemDetailsViewModel(0, item1, item2, GrandTotal);
RDcViewModel.push(rdtCViewModel);
}
var obj = new ReportViewModel(recordId, RDcViewModel);
var viewmodel = JSON.stringify(obj);
return viewmodel;
}
I have the above sample function that i'm using to iterate over html table rows and storing the row values in an array.
Once i have my array populated, i'm using below code snippet to post the data to my controller.
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
//i want to check from here if viewmodel has any item(row) where GrandTotal is 0 (zero)
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function (data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function (e) {
return false;
}
});
});
}
What i now want to do in my PostData function is to check if my "viewmodel" object contains any item(row) where "GrandTotal" is 0.
using JSON.parse(viewmodel), prepare object of type ReportViewModel with RDcViewModel JS array of type ItemDetailsViewModel and iterate over it to find if any grandtotal == 0 for ItemDetailsViewModel instances
var viewmodel = GetViewModelData(),
var obj = JSON.parse(viewmodel);
var bFoundZero=false;
$.each(obj.RDcViewModelArray, function(idx, elem){
if( elem.GrandTotal === 0 ) bFoundZero=true;
})
if( bFoundZero ) return 0;
As you have stringified it, now you have to parse it back if you want to access its keys and values:
var PostData = function() {
$(".btnSubmit").click(function() {
var viewmodel = GetViewModelData(),
viewObj = JSON.parse(viewmodel),
flag = false; // <-----parse it back here
viewObj.forEach(function(i, el){
flag = el.GrandTotal === 0;
return flag;
});
if(flag){ return false; } // <------ and stop it here.
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function(data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function(e) {
return false;
}
});
});
}
There is no point iterating array again. Break the loop in GetViewModelData() and return false from that function. Then test it in PostData
Inside existing for loop:
var GrandTotal = (item1 + item2);
if(!GrandTotal){
return false;
}
Then in PostData()
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
if(viewmodel === false){
alert('Missing total');
return; //don't proceed
}
/* your ajax */
I am using a script to get specified contents of specific links on a webpage and it has worked fine before, but after the site changed to https, it has stopped working.
The script is as follows:
var URL = window.location.origin
var episodeLinks = $('table.listing a').map(function(i,el) { return $(el).attr('href'); });
$.ajaxSetup({async:false});
$.getScript("https://kissanime.com/Scripts/asp.js");
var login = "vergo777";
var api_key = "R_6a13f014b38f4f80a31cf7d80a7c18c7";
var long_url;
var startEpisode;
do {
startEpisode = prompt("Enter episode number you want to start from");
if(startEpisode <= 0 || startEpisode > episodeLinks.length) {
alert("Episode number entered must be greater than 0 and lesser than total number of eps");
} else {
break;
}
} while(true);
var endEpisode;
do {
endEpisode = prompt("Enter episode number you want to end at");
if(endEpisode <= 0 || endEpisode > episodeLinks.length || endEpisode < startEpisode) {
alert("Episode number entered must be greater than 0 and lesser than total number of eps");
} else {
break;
}
} while(true);
var videoQuality = prompt("Enter video quality you want to download. Example - '960x720.mp4' (without the quotes)");
var i;
for (i = (episodeLinks.length - startEpisode); i >= (episodeLinks.length - endEpisode); i--) {
jQuery.ajax({
url: URL + episodeLinks[i],
success: function(result) {
var $result = eval($(result));
var stringStart = result.search("var wra");
var stringEnd = result.search("document.write");
var javascriptToExecute = result.substring(stringStart, stringEnd);
eval(javascriptToExecute);
$("body").append('<div id="episode' + i + '" style="display: none;"></div>')
$('#episode' + i).append(wra);
var downloadQualityOptions = $('#episode' + i + ' a').map(function(i,el) { return $(el); });
var j;
for(j = 0; j < downloadQualityOptions.length; j++) {
if(videoQuality === downloadQualityOptions[j].html()) {
long_url = downloadQualityOptions[j].attr('href');
console.log(i);
get_short_url(long_url, login, api_key);
}
}
},
async: false,
script: true
});
}
function get_short_url(long_url, login, api_key)
{
$.getJSON(
"http://api.bitly.com/v3/shorten?callback=?",
{
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": long_url,
async: true
},
function(response)
{
console.log(response.data.url);
}
);
}
I am getting the error: Uncaught ReferenceError: asp is not defined(…)
Any help is very appreciated, thank you!
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);
});