How can I loop into the objects of a DTO in Ajax? - javascript

I'm trying to GET all players from a list, but the whole GetMapping it's constructed around Player DTO. The data I want to loop is a list of "players" stored into a DTO like this:
{
PLAYERS: [
{ player0 {parameters...} },
{ player1 {parameters...} },
...
]
}
Here is my ajax code in JS:
//GET ALL PLAYERS
function getAllPlayers() {
document.getElementById("erase_repeated_results").innerHTML = ""; //to erase info I don't want to store
document.getElementById("fullInfo").innerHTML = "";
document.getElementById("data").innerHTML = "";
document.getElementById("sameRoles").innerHTML = "";
$.ajax({
type: "GET",
url: "http://localhost:8081/dices/players",
contentType: "application/json",
dataType: "json",
success: function (data) {
for (var j = 0; j < data.length; j++) {
document.getElementById("fullInfo").innerHTML += "Complete info of player " + (j+1) + ": " + "<br />" + "<br />" +
"The ID of this player is: " + data[j].id + "<br />" +
"The name of this player is: " + data[j].name + "<br />" +
"The register date of this player is: " + data[j].registerDate + "<br />" +
"The total amount of dice rolls of this player is: " + data[j].totalDiceRolls + "<br />" +
"The total amount of games won of this player is: " + data[j].gamesWon + "<br />" +
"The success rate of this player is: " + data[j].successRate + "<br />";
console.log(data[j]);
}
},
error: function () {
alert("Something went wrong! Maybe you are entering parameters not related to our Database!");
}
});
}
Below I attached a screenshot so you can see how it is working while I debug it, and you'll see in the scope section what I'm talking about.
How can I enter only in the array parameter of the DTO?

In your data structure, it's the PLAYERS property which is an array. data is an object containing a single property called PLAYERS. So looping through that makes no sense. Just loop through the players array instead:
for (var j = 0; j < data.PLAYERS.length; j++) {
document.getElementById("fullInfo").innerHTML += "Complete info of player " + (j+1) + ": " + "<br />" + "<br />" +
"The ID of this player is: " + data.PLAYERS[j].id + "<br />" +
"The name of this player is: " + data.PLAYERS[j].name + "<br />" +
"The register date of this player is: " + data.PLAYERS[j].registerDate + "<br />" +
"The total amount of dice rolls of this player is: " + data.PLAYERS[j].totalDiceRolls + "<br />" +
"The total amount of games won of this player is: " + data.PLAYERS[j].gamesWon + "<br />" +
"The success rate of this player is: " + data.PLAYERS[j].successRate + "<br />";
console.log(data.PLAYERS[j]);
}

Related

Can this be turned into a for loop?

I would like to clean this up with a For loop. What would be the most efficient way coding this out?
I'm creating a search form that looks through a database for the specific form criteria. The way I have it coded would only work for the 8 Fields. But it is possible for the search form to have more then 8. For now though, I'd like to be able to map the results and display in a results page.
This is what I tried. This did not work at all and probably make no sense to anyone lol.
var obj =data[0]
$.get("obj", {data: $('select["Fields.DisplayName" + Fields.DataValue]').val()},
function(data){
$.each(data, function(i, item) {
alert(item);
});
}
);
This works for getting the data and displaying it how I'd like.
var obj = data[0];
document.getElementById("test").innerHTML =
"<p>"+ obj.Fields[0].DisplayName + ": " + obj.Fields[0].DataValue + "</p>" +
"<p>" + obj.Fields[1].DisplayName + ": " + obj.Fields[1].DataValue + "</p>" +
"<p>"+ obj.Fields[2].DisplayName + ": " + obj.Fields[2].DataValue + "</p>" +
"<p>"+ obj.Fields[3].DisplayName + ": " + obj.Fields[3].DataValue + "</p>" +
"<p>" + obj.Fields[4].DisplayName + ": " + obj.Fields[4].DataValue + "</p>" +
"<p>" + obj.Fields[5].DisplayName + ": " + obj.Fields[5].DataValue + "</p>" +
"<p>"+ obj.Fields[6].DisplayName + ": " + obj.Fields[6].DataValue + "</p>" +
"<p>" + obj.Fields[7].DisplayName + ": " + obj.Fields[7].DataValue + "</p>"
;
The next problem is if there is more then 1 data object. Currently I have it set to loop through the first object, but when I remove that I get cannot read property of '0' undefined.
Sure.
var html = "";
obj.Fields.forEach(({DisplayName, DataValue}) => {
html += `<p>${DisplayName}: ${DataValue}</p>`;
});
document.getElementById("test").innerHtml = html;
Use Array.map() and join the results:
var fields = data[0].Fields ;
document.getElementById("test").innerHTML = fields
.map(function(field) {
return '<p>' + field.DisplayName + ': ' + field.DataValue + '</p>';
})
.join('\n');

Unable to properly add value to a cell using GAS

I adopted the script below and I am having two issues.
The "Email Sent" value does not update in the correct row. Let's say I sent an email to the recipient in row 5, instead of appearing in column 10 of row 5 "Email Sent" appears in column 10 of row 21.
Sometimes "Email Sent" does not appear at all even though I know the email went out.
I've tried everything I can think of but I can't make it work.
//Send approval or non-approval of time off request
function sendLeaveRequestDecisions() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Form Responses 2");
var dataRange = sheet.getRange(2,1,sheet.getLastRow()-1,sheet.getLastColumn());
var data = dataRange.getValues();
for (i in data) {
var startRow = 2; //First row of data to process
var rowData = data [i];
var startdate = rowData [2];
var enddate = rowData [3];
var type = rowData [4];
var email = rowData [5];
var recipient = rowData [1];
var decision = rowData [7];
var comments = rowData [8];
var emailstatus = rowData [9]
var emailPattern = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|aero|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|name|museum|name|net|org|pro|tel|travel)\b/;
var validEmailAddress = emailPattern.test(email);
if (validEmailAddress == true && emailstatus != "Email Sent") {
var message = "<HTML><BODY>"
+ "<P>Dear " + recipient + ","
+ "<br /><br />"
+ "<P>The following request:"
+ "<br /><br />"
+ "<b>Type: </b>" + type + "<br />"
+ "<b>From: </b>" + startdate + "<br />"
+ "<b>To: </b>" + enddate + "<br />"
+ "<br /><br />"
+ "<b>is </b>" + decision + "<br />"
+ "<b>Comments </b>" + comments + "<br />"
+ "<br /><br />"
+ "Diane"
+ "<br /><br />"
+ "</HTML></BODY>";
MailApp.sendEmail(email, "Regarding your leave request", "", {htmlBody: message});
sheet.getRange(i + 2,10).setValue("Email Sent");
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
Try this:
Mostly what was wrong was that you didn't escape the forward slashes contained in your regex expression. I'm surprised it ran at all. It runs okay for me. You might like to take a look at Utilities.formatString() for building your message. Just click on Help/API Reference. From there it's down at the bottom left where it says Script Service/Utilities.
Personally, I wouldn't put flush in a loop like that. I moved startRow and emailPattern out of the loop as well. They don't change. The less you put in a loop the faster it runs. I commented out the MailApp.sendmail because I didn't actually want to send email and I assume that you got that right.
function sendLeaveRequestDecisions() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Index Generation");
var dataRange = sheet.getRange(2,1,sheet.getLastRow()-1,sheet.getLastColumn());
var data = dataRange.getValues();
var startRow = 2; //First row of data to process
var emailPattern = /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|aero|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|name|museum|name|net|org|pro|tel|travel)\b/;
for (var i=0;i<data.length;i++){
var rowData = data [i];
var startdate = rowData[2];
var enddate = rowData[3];
var type = rowData[4];
var email = rowData[5];
var recipient = rowData[1];
var decision = rowData[7];
var comments = rowData[8];
var emailstatus = rowData[9];
var validEmailAddress = emailPattern.test(email);
if (validEmailAddress == true && emailstatus != "Email Sent") {
var message = "<HTML><BODY>" + "<P>Dear " + recipient + "," + "<br /><br />" + "<P>The following request:" + "<br /><br />" + "<b>Type: </b>" + type + "<br />" + "<b>From: </b>" + startdate + "<br />" + "<b>To: </b>" + enddate + "<br />" + "<br /><br />" + "<b>is </b>" + decision + "<br />" + "<b>Comments </b>" + comments + "<br />"+ "<br /><br />" + "Diane"+ "<br /><br />" + "</HTML></BODY>";
//MailApp.sendEmail(email, "Regarding your leave request", "", {htmlBody: message});
sheet.getRange(i + 2,10).setValue("Email Sent");
}
}
//SpreadsheetApp.flush();
}
I did something similar but quite differently and I've personally found this kind of response unhelpful in the past so do tell me to leave it alone if you feel like that.
If you would like me to try writing something though, which you and others could run, I will do that. My example of doing this is as personal - even more so - than yours.

Storing data from a select tag to a string using Javascript

I'm trying to take information out of a form controlled by a select statement and store it in a string. The plan is to send the information gathered from the user via email, which I used PHP to do. I have an idea how to do it (a while loop that's controlled by how many lines are in the list,) but I can't quite gather the information.
Here's the loop:
var empMessage = function(){
messageString = "";
var noEmp = $("#drpEmp option").length;
var i = 0;
$("#drpEmp").selector.index = i;
while (i < noEmp){
$("#drpEmp").index = i;
messageString = messageString +
"Name: " + firstName.val + " " + MI.val + " " + lastName.val + "<br/>" +
"Business: " + BusinessName.val + "<br/>" +
"Address: " + address.val + "<br/>" +
" " + city.val + ", " + state.val + " " + zip.val + "<br/>";
}
messageString = "<strong>Employee Information</strong><br/>" . messageString;
i++;
}
$("#stringHolder").val(messageString);
}
Here's the JS Fiddle:
https://jsfiddle.net/xptxz7by/3/
I know I probably really off. I know I have the loop working and the list is getting counted, but I can't seem to retrieve the information. I'm also thinking I'm approaching sending the information wrong and there's probably a better way of doing it, I just haven't figured out how.
The data you want is in the Employee object that you saved in each option's .data(), so you need to get that data and use the properties.
messageString = "<strong>Employee Information</strong><br/>";
$("drpEmp option:selected").each(function() {
var employee = $(this).data("employee");
messageString +=
"Name: " + employee.firstName + " " + employee.MI + " " + lastName + "<br/>" +
"Business: " + employee.BusinessName + "<br/>" +
"Address: " + employee.address + "<br/>" +
" " + employee.city + ", " + employee.state + " " + employee.zip + "<br/>";
});

JavaScript inserting images

Hi I'm trying to insert specific images on specific pages when each pages loads and i just cant seem to get it, my code looks like this
function display() {
coursetitle = (x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
coursecode = (x[i].getElementsByTagName("code")[0].childNodes[0].nodeValue);
enrolledyear = (x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue);
semester = (x[i].getElementsByTagName("semester")[0].childNodes[0].nodeValue);
labday = (x[i].getElementsByTagName("labday")[0].childNodes[0].nodeValue);
lectureday = (x[i].getElementsByTagName("lectureday")[0].childNodes[0].nodeValue);
description = (x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue);
graphic = (x[i].getElementsByTagName("graphic")[0].childNodes[0].nodeValue);
document.getElementById("show").innerHTML = "Title: " + coursetitle + "<br />Code: " +
+ coursecode + "<br />Year: " + enrolledyear + "<br />Semester:" + semester +
"<br />Lab Day:" + labday + "<br />Lecture Day:" + lectureday +
"<br />Course Description:<br/>" + description;
What should i do?
If graphic value has the image path
document.getElementById("show").innerHTML = "Title: " + coursetitle + "<br />Code: " +
+ coursecode + "<br />Year: " + enrolledyear + "<br />Semester:" + semester +
"<br />Lab Day:" + labday + "<br />Lecture Day:" + lectureday +
"<br />Course Description:<br/>" + description + "</br> <img src=\""+graphic +"\" /> ";

Maintaining Line Breaks Through Facebook API Usage

When using the api and javascript to display the description of an event, how can i preserve the line breaks?
query.wait(function(rows) {
document.getElementById('debug').innerHTML =
new Date(rows[0].start_time * 1000) + "<br />" +
rows[0].start_time + "<br />" +
rows[0].end_time + "<br />" +
rows[0].location + ", " +
rows[0].venue['street'] +
rows[0].venue['city'] + ", " +
rows[0].venue['state'] + "<br />" +
rows[0].description;
;
});
You can use a <pre> element to preserve white space characters, such as \t and \n.

Categories

Resources