Script only working in the console even with document.ready - javascript

I have a script that runs on a page. It doesn't work, but when I type it into the console then run it it works perfectly.
This might sound like other questions such as this one, but I already have $(document).ready(). All the variables already defined here have been defined earlier in the document.
$(document).ready(function(){
for (var i = 0; i < posts.length; i++) {
var post_html = posts_html[i];
var link = posts[i];
console.log(i);
name = $(post_html)[5].childNodes[1].innerHTML;
document.getElementsByClassName('posts')[0].innerHTML = document.getElementsByClassName('posts')[0].innerHTML + '<li>' + name + '</li>'
console.log(name + ' - ' + posts + ' - ' + i + ' - ' + posts[i] + ' - ' + link);
}
});

Add setTime out function in your code.please try below code:
$(document).ready(function(){ setTimeout(function(){
for (var i = 0; i < posts.length; i++) {
var post_html = posts_html[i];
var link = posts[i];
console.log(i);
name = $(post_html)[5].childNodes[1].innerHTML;
document.getElementsByClassName('posts')[0].innerHTML = document.getElementsByClassName('posts')[0].innerHTML + '<li>' + name + '</li>'
console.log(name + ' - ' + posts + ' - ' + i + ' - ' + posts[i] + ' - ' + link);
}
},5000);});

Related

MVC Java script loop async controller data

I'm running a script and want to output an alert when it is finished loading all data.
The problem is, I have a for loop and call a MVC controller function,
but the alert is outputted/triggered bevor the data is loaded completely.
It seems like the data fetching from the controller runs asynchronously.
I added the async and await but it changed nothing.
Script:
async function checkform() {
$("#faRueckmeldungen").html("")
let _clipboard="";
var _fanr = $('#FaNr').val();
var _faArray = _fanr.replace(/\n/g, " ").split(" ");
for (var i = 0; i <= _faArray.length; i++) {
var _fA = _faArray[i];
if (_fA < 2013810000) {
(document.getElementById("FaNr")).style.backgroundColor = "OrangeRed";
alert("FaNr #" + _fA + " nicht korrekt!");
}
else {
var url = "/FaInfos/FaRueckmeldung";
$.get(url, { faNr: _fA }, await function (data) {
$("#faRueckmeldungen").append(data[0]);
_clipboard += data[1];
navigator.clipboard.writeText(_clipboard);
})
}
}
alert("finished")
}
Controller function:
public JsonResult FaRueckmeldung(string faNr)
{
if (faNr == null)
return null;
//Loading data from SAP
var faHead = SapInterClient.GetFaHead(faNr.ToString());
var faPos = SapInterClient.GetFaPos(faNr.ToString());
//<td>"++"</td>
string clippoard = "Fertigungsauftrag\tMaterialnummer\tAuftragsmenge\tStart Termin Soll\tStart Termin Ist\tEndtermin Soll\tEndtermin Ist\tPersonal Soll [min]\tPersonal Ist [min]";
string sret = "<table class=" + (char)34 + "table1" + (char)34 + #"><thead><tr>
<th>Fertigungsauftrag</th>
<th>Materialnummer</th>
<th>Auftragsmenge</th>
<th>Start Termin Soll</th>
<th>Start Termin Ist</th>
<th>Endtermin Soll</th>
<th>Endtermin Ist</th>
<th>Personal Soll [h]</th>
<th>Personal Ist [h]</th>";
decimal VgPers = 0;
decimal RuPers = 0;
for (int i = 0; i < faPos.RückgemeldeteLeistungRP.Count(); i++)
{
VgPers += faPos.RückgemeldeteLeistungTP[i];//VorgabePersonal
RuPers += faPos.RückgemeldeteLeistungRP[i];//FeedbackPersonal
}
string cellColor = "LightGreen";
if (VgPers/60 < RuPers)
cellColor = "Salmon";
foreach (var item in faPos.Vorgangsnummer)
{
clippoard += "\t VG " + item;
sret += "<th> VG " + item + "</th>";
}
clippoard += "\r\n";
sret += "</tr></thead>";
sret += "<tr><td>" + faNr + "</td><td>" + faHead.MatNr + "</td><td>" + faHead.GesamteAuftragsmenge + "</td><td>" + faHead.TerminierterStart.ToString("dd.MM.yyyy") + "</td><td>" + faHead.IstStartTermin.ToString("dd.MM.yyyy") + "</td><td>" + faHead.TerminiertesEnde.ToString("dd.MM.yyyy") + "</td><td>" + faHead.IstEndTermin.ToString("dd.MM.yyyy") + "</td><td>" + String.Format("{0:0.00}", VgPers / 60) + "</td><td bgcolor=" + (char)34 + cellColor + (char)34 + ">" + String.Format("{0:0.00}", RuPers) + "</td>";
clippoard += faNr + "\t" + faHead.MatNr + "\t" + faHead.GesamteAuftragsmenge + "\t" + faHead.TerminierterStart.ToString("dd.MM.yyyy") + "\t" + faHead.IstStartTermin.ToString("dd.MM.yyyy") + "\t" + faHead.TerminiertesEnde.ToString("dd.MM.yyyy") + "\t" + faHead.IstEndTermin.ToString("dd.MM.yyyy") + "\t" + String.Format("{0:0.00}", VgPers / 60) + "\t" + String.Format("{0:0.00}", RuPers);
for (int i = 0; i < faPos.GutmengeGesamt.Count(); i++)
{
clippoard += "\t" + faPos.GutmengeGesamt[i];
sret += "<td>" + faPos.GutmengeGesamt[i] + "</td>";
}
clippoard += "\r\n";
sret += "</tr></table>";
return Json(new List<string>{sret,clippoard}, JsonRequestBehavior.AllowGet);
}
Please help.
Best regards Simon
You forgot to add await before the $.get(url....). The await before function has no reason to be there. Add async if you make asynchronous calls in there, though I do not see any.
The idea is that you add await to the specific instruction that works asynchronously ( and you want to wait for it). In your case, your callback function that you send to get is not the async function, rather the .get() itself is the guy you're looking for. The callback function you send there is being executed after the api call is done, and it's handled by .get() itself.
So your code will look a little something like this:
await $.get(
url,
{ faNr: _fA },
function (data) {
$("#faRueckmeldungen").append(data[0]);
_clipboard += data[1];
navigator.clipboard.writeText(_clipboard);
}
)

I wan to print my text into the <div> tag, but it doesn't print

This is my Ajax Function
function xhttp() {
// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();
var hourArray;
// Define a callback function
xhttp.onload = function () {
var parser, xmlDoc;
var text = this.responseText;
parser = new DOMParser();
xmlDoc = parser.parseFromString(text, "text/xml");
hourArray = xmlDoc.getElementsByTagName("item");
booking_hours(hourArray);
};
// Send a request
xhttp.open("GET", "test.xml");
xhttp.send();
}
When any is clicked ajax function will work
dataCel.on("click", function () {
var thisEl = $(this);
var thisDay = $(this).attr("data-day").slice(8);
var thisMonth = $(this).attr("data-day").slice(5, 7);
$(".c-aside__num").text(thisDay);
$(".c-aside__month").text(monthText[thisMonth - 1]);
$(".c-aside__year").text(dateObj.getUTCFullYear() + indexYear);
xhttp();
dataCel.removeClass("isSelected");
thisEl.addClass("isSelected");
});
When ajax will work I want to read hours to my text and print this text into div tag
function booking_hours(hourArray) {
var table;
for (var i = 0; i < hourArray.length; i++) {
if (parseInt(hourArray[i].childNodes[0].nodeValue) < 9)
table +=
"<div data-hours='0" +
hourArray[i].childNodes[0].nodeValue +
".00-0" +
(parseInt(hourArray[i].childNodes[0].nodeValue) + 1) +
".00' class='hour_cell'>" +
"<p>" +
"0" +
hourArray[i].childNodes[0].nodeValue +
".00 - 0" +
(parseInt(hourArray[i].childNodes[0].nodeValue) + 1) +
".00" +
"</p></div>";
else if (parseInt(hourArray[i].childNodes[0].nodeValue) == 9) {
table +=
"<div data-hours='0" +
hourArray[i].childNodes[0].nodeValue +
".00-0" +
(parseInt(hourArray[i].childNodes[0].nodeValue) + 1) +
".00' class='hour_cell'>" +
"<p>" +
"0" +
hourArray[i].childNodes[0].nodeValue +
".00 - " +
(parseInt(hourArray[i].childNodes[0].nodeValue) + 1) +
".00" +
"</p></div>";
} else {
table +=
"<div data-hours='" +
hourArray[i].childNodes[0].nodeValue +
".00-" +
(parseInt(hourArray[i].childNodes[0].nodeValue) + 1) +
".00' class='hour_cell'>" +
"<p>" +
hourArray[i].childNodes[0].nodeValue +
".00 - " +
(parseInt(hourArray[i].childNodes[0].nodeValue) + 1) +
".00" +
"</p></div>";
}
}
console.log(table.slice(9));
document.getElementsById("hoursList").innerHTML = table.slice(9);
}
This console log print this console.log(table.slice(9));
<div data-hours='02.00-03.00' class='hour_cell'><p>02.00 - 03.00</p></div><div data-hours='08.00-09.00' class='hour_cell'><p>08.00 - 09.00</p></div><div data-hours='10.00-11.00' class='hour_cell'><p>10.00 - 11.00</p></div><div data-hours='16.00-17.00' class='hour_cell'><p>16.00 - 17.00</p></div>
But this innerHTML doesn't print what console log printed
document.getElementsById("hoursList").innerHTML = table.slice(9);
Div tag that I want to use.
<div id="hoursList" class="hours__list"></div>

Cannot read item in nested array?

I have a nested array inside a list like the following:
{total_results, page, results [id, species_guess, observed_on_details {date, week, month, hour, year}]}
I am trying to get just the id, species_guess, and date using forEach.
function observationSummary2(data) {
data.results.forEach(element =>
console.log('#' + data.results.id +
" - " + data.results.species_guess +
' (' + data.results.observed_on_details.date + ')')
);
}
This is saying " Cannot read property 'date' of undefined ". I have tried using a for loop like this and it worked just fine.
for (let i = 0; i < data.results.length; i++) {
console.log('#' + data.results[i].id + " - " + data.results[i].species_guess + ' (' + data.results[i].observed_on_details.date + ')');
}
Can anyone tell me where am I doing wrong here, sorry I am still new at this language.
you should use foreach as follow
function observationSummary2(data) {
data.results.forEach(element =>
console.log('#' + element.id +
" - " + element.species_guess +
' (' + element.observed_on_details.date + ')')
);
}
Instead of
function observationSummary2(data) {
data.results.forEach(element =>
console.log('#' + data.results.id +
" - " + data.results.species_guess +
' (' + data.results.observed_on_details.date + ')')
);
}
Replace "data.results" with "element"
function observationSummary2(data) {
data.results.forEach(element =>
console.log('#' + element.id +
" - " + element.species_guess +
' (' + element.observed_on_details.date + ')')
);
}
More info about "forEach()" here:
https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

How can I filter null or undefined values from an ajax call?

I'm trying to create a simple class directory for my kid's class. I have a Array of students in JSON format and wrote an AJAX call for the kids' names, and parents information. But some don't have two parents or two sets of contact information? I have tried "if (studentData !== null) {
show the data} but that doesn't work.
function showStudents() {
var currentURL = window.location.origin;
$.ajax({ url: currentURL + '/api/students', method: 'GET'})
.then(function(studentData) {
console.log("------------------------------------");
console.log("URL: " + currentURL + "/api/students");
console.log("------------------------------------");
// Here we then log the NYTData to console, where it will show up as an object.
console.log(studentData);
console.log("------------------------------------");
for (var i = 0; i < studentData.length; i++ ) {
var studentSection = $('<div>');
studentSection.addClass('card');
studentSection.attr('id', 'studentCard-' + i);
studentSection.attr('style', 'width:25rem');
$('#studentSection').append(studentSection);
$('#studentCard-' + i ).append('<div class="card-header"><h3>' + studentData[i].firstName + ' ' + studentData[i].lastName + '</h3></div>');
$('#studentCard-' + i ).append('<ul class="list-group list-group-flush>');
$('#studentCard-' + i ).append('<li class="list-group-item"><h5>Parent(s):</h5>' + studentData[i].parent1 + ' & ' + studentData[i].parent2 +' </li>');
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact1 + '<br> email: ' + studentData[i].email1 + '</li>');
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact2 + '<br> email: ' + studentData[i].email2 + '</li>');
$('#studentCard-' + i ).append('</ul>');
$('#studentCard-' + i ).append('</div>');
}
});
}
It sounds like it's the parent1 or parent2 properties that might not exist, and the contact1 or contact2 properties that might not exist. It doesn't make sense to test if the entire response is null - just check those properties instead. For example:
for (var i = 0; i < studentData.length; i++ ) {
var studentSection = $('<div>');
studentSection.addClass('card');
studentSection.attr('id', 'studentCard-' + i);
studentSection.attr('style', 'width:25rem');
$('#studentSection').append(studentSection);
$('#studentCard-' + i ).append('<div class="card-header"><h3>' + studentData[i].firstName + ' ' + studentData[i].lastName + '</h3></div>');
$('#studentCard-' + i ).append('<ul class="list-group list-group-flush>');
// Start of changes
const parentStr = [studentData[i].parent1, studentData[i].parent2].filter(Boolean).join(' & ');
$('#studentCard-' + i ).append('<li class="list-group-item"><h5>Parent(s):</h5>' + parentStr +' </li>');
if (studentData[i].contact1) {
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact1 + '<br> email: ' + studentData[i].email1 + '</li>');
}
if (studentData[i].contact2) {
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact2 + '<br> email: ' + studentData[i].email2 + '</li>');
}
// End of changes
$('#studentCard-' + i ).append('</ul>');
$('#studentCard-' + i ).append('</div>');
}
Your script structure could be improved too - unless each card's id is particularly important, it would make more sense to use a class instead of unique ids for every single element, or perhaps to leave it off entirely if you're only using it to select the newly created container. You already have a reference to the element you just created with studentSection, so just reference that variable again. You can also use method chaining to reduce your syntax noise:
CSS:
.card {
width: 25rem;
}
(that will keep you from having to manually set the width of each created element in your JS)
JS loop:
for (var i = 0; i < studentData.length; i++ ) {
var studentSection = $('<div>');
$('#studentSection').append(studentSection);
const parentStr = [studentData[i].parent1, studentData[i].parent2].filter(Boolean).join(' & ');
studentSection.addClass('card')
.append('<div class="card-header"><h3>' + studentData[i].firstName + ' ' + studentData[i].lastName + '</h3></div>')
.append('<ul class="list-group list-group-flush>')
.append('<li class="list-group-item"><h5>Parent(s):</h5>' + parentStr +' </li>');
if (studentData[i].contact1) {
studentSection.append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact1 + '<br> email: ' + studentData[i].email1 + '</li>');
}
if (studentData[i].contact2) {
studentSection.append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact2 + '<br> email: ' + studentData[i].email2 + '</li>');
}
studentSection.append('</ul>');
.append('</div>');
}
(Or, even better, use template literals instead)

jQuery When After Each Loop

I have six static html questions and then 3-4 questions being generated by JSON dynamically based upon a form choice made on a page before. What I'm trying to do is generate the questions, then create a progress bar based on the final number of questions created. Where I'm having trouble is using the jQuery when done method after my each loop. It is firing after the first iteration instead of the last. I have tried populating an array "Qs" and passing the array, after reading some other posts, but what I have hasn't worked. I would really like to segment my code and clean it up as much as possible, so I'm trying to stay away from nesting it.
var Qs = [];
var generateQs = function (){
var $dept = sessionStorage.getItem("sFGeneralDepartment1");
var $qWrapper = $("#assessmentTool");
$.getJSON("js/dept-questions.json", function(data) {
var key = $dept;
var vals = [];
switch(key) {
case 'Information technology':
vals = data.IT;
break;
case 'Finance':
vals = data.FIN;
break;
case 'Human resources':
vals = data.HR;
break;
case 'Marketing':
vals = data.MKT;
break;
default:
vals = data.OT;
break;
}
$.each(vals, function(index, value) {
var $cleanID = (value.qID).replace(/q/g, '');
$qWrapper.append('<div class="question-container rangeIcon disabled" id="' + value.qID + '"><p>Question ' + $cleanID +'</p> <h4>' + value.questionText + '</h4><ul class="answer-container"></ul></div>');
$.each(value.answers, function(i, answer) {
var $aID = answer.aID;
var $radioBtn = '<div class="radioBtn"><span class="radioBtnInner"></span></div>';
$('.question-container#' + value.qID + ' .answer-container').append('<li class="survey-item"><div class="icon-holder" id="' + $aID + '"><img src="img/' + answer.iconFileName + '" width="' + answer.iconWidth +'" height="'+ answer.iconHeight + '"/></div><input type="radio" id="'+ $aID + '" value="' + answer.pointValue + '"><label for="' + $aID + '" class="radio" data-popover="'+ answer.popoverText + '">' + $radioBtn + '<span class="labelTopText">' + answer.labelTopText + '<span class="divider">/</span></span><span class="labelBottomText">' + answer.labelBottomText + '</span></label></li>');
});
Qs.push($cleanID);
});
console.log('done');
console.log(Qs);
});
};
$.when(generateQs($,Qs)).done(function() {
//create progress bar
console.log('starting');
var qCount = ($('.question-container').length + 1);
var qList = $('#progressBar');
for (var i = 0; i < qCount; i++){
qList.append('<li class="progress-bar-steps" data-item="q' + (i+1) + '">' + '<span class="step-text">' + (i+1) + '</span>' + '</li>');
$('.question-container').each(function (i, value){
var qId = $(this).attr('id');
if ($(this).hasClass("active")) {
$(this).css('opacity','1.0');
$('#progressBar').find("[data-item='" + qId + "']").addClass('active').html('<span class="step-text">' + (i+1) + '</span>');
$('.progress-bar-steps.active').next('.progress-bar-steps').addClass('next disabled-next').html('<span class="step-text">' + (i+2) + '</span>');
} else {
$(this).addClass('disabled');
}
});
}
});

Categories

Resources