Add elements in the DOM with JS - javascript

I'm trying to print in the HTML the data from another part of the site, the data appears on the console, however not in the HTML.
I believe it is an error in the code, could someone point me or direct me?
$.ajax({
type: "GET",
url: 'https://example.com',
crossDomain: true,
success: function (json) {
var reservas = json;
reservas.forEach(function (reserva) {
$(".reservas").append($("<td/>", {
html: reserva
}));
console.log(reserva);
});
},
error: function (e) {
console.log(e);
}
});
If i change the variable reservas for:
var reservas = ["test", "test2", "test3"]
And the elements are being added..
when I give console.log (reserve), the console return:
Object {
_id: "10152686662737642",
nome: "First Person",
email: "email1#gmail.com",
__v: 0
}(index):68
Object {
_id: "10152433045473800",
nome: "Second Person",
email: "email2#gmail.com",
__v: 0
} (index):68
maybe the problem is that is not an array?

Based on your clarifications. I believe what you want to do is:
$(".reservas").append($("<td/>", {
html: JSON.stringify(reserva)
}));
either that or $(".reservas") isn't finding any elements in the DOM. Also you may want to do something like:
$(".reservas").append($("<td/>", {
html: reserva.nome + " " + reserva.email
}));
instead depending on what you actually want to display

Related

Posting google form results to discord via webhook failing

I've been using this script for many months to post the results of a google form to a private discord channel via webhook and have had no problems with it. Recently (2 to 3 weeks) it stopped functioning, and I can't get it to work on this one form. The form has less than 10 questions, and It still works on other forms of similar size for reasons i can not understand. I've very novice, but I did try looking for a solution and tried adding an option to it but I wasn't good enough to get it right.
I get the following error when trying to execute the script.
Exception: Request failed for https://discord.com returned code 400. Truncated server response: {"embeds": ["0"]} (use muteHttpExceptions option to examine full response)
at onSubmit(Code:31:15)
var POST_URL = "https://discord.com/api/webhooks/xxxxxxxxx";
function onSubmit(e) {
var discordPayload = {
content: "New Form Submitted",
embeds: [
{
type: "rich",
title: "Form Entry",
color: 307506,
fields: []
}
]
};
e.response.getItemResponses().forEach(function (i) {
var v = i.getResponse() || "None";
if (!Array.isArray(v))
discordPayload.embeds[0].fields.push({
name: i.getItem().getTitle(),
value: v
});
else
discordPayload.embeds[0].fields.push({
name: i.getItem().getTitle(),
value: v.toString()
});
});
UrlFetchApp.fetch(POST_URL, {
method: "post",
payload: JSON.stringify(discordPayload),
contentType: "application/json"
});
} var POST_URL = "https://discord.com/api/webhooks/1015107674817437696/vcacU2A4qx_oK3rrFMw6fbXJUon9tR1ctp93ICZ_mDC2_wzbQF1S6s7Nrh56BQG7forc";
function onSubmit(e) {
var discordPayload = {
content: "New Form Submitted",
embeds: [
{
type: "rich",
title: "Form Entry",
color: 307506,
fields: []
}
]
};
e.response.getItemResponses().forEach(function (i) {
var v = i.getResponse() || "None";
if (!Array.isArray(v))
discordPayload.embeds[0].fields.push({
name: i.getItem().getTitle(),
value: v
});
else
discordPayload.embeds[0].fields.push({
name: i.getItem().getTitle(),
value: v.toString()
});
});
UrlFetchApp.fetch(POST_URL, {
method: "post",
payload: JSON.stringify(discordPayload),
contentType: "application/json"
});
}

How to structure a JSON call

I have an endpoint which I call with Axios and the response looks like (for example):
items: [
{
url: "https://api.example1...",
expirationDate: "2019-11-15T00:00:00+01:00"
},
{
url: "https://api.example2...",
expirationDate: "2019-12-20T00:00:00+01:00"
},
{
url: "https://api.example3...",
expirationDate: "2020-01-17T00:00:00+01:00"
},
...and so on.
If I go to one of the url:s in the browser the structure of the JSON is:
fooBar: {
url: "https://api.foo...",
id: "123",
type: "INDEX",
source: "Foobar",
quotes: {
url: "https://api.bar..."
}
},
I need to get the quotes of the two first url:s in items:[] dynamically because they will disappear when the 'expirationDate' is older than today's date.
How can this be achieved? Thanks in advance!
If I understand the requirements correctly you need to:
get the list of items
get item details for first two items (to extract links to quotes)
get quotes for first two items
You can use promise chaining to execute these operations maintaining the order:
const getQuotes = (item) => axios.get(item.url)
.then(resp => axios.get(resp.data.fooBar.quotes.url));
axios.get('/items') // here should be the url that you use to get items array
.then(resp => resp.data.slice(0, 2).map(getQuotes))
.then(quotes => Promise.all(quotes))
.then(quotes => {
console.log(quotes);
});
Please find my proposal below. I gave two examples. You can get the whole quotes object, or just the URL inside the quotes object.
This is just a console log, but you can easily ie. append this data to a div in the html or pass this URL to some other function.
$(function() {
const address = 'https://api.example1...';
function loadQuotes() {
$.ajax({
url: address,
dataType: 'json',
}).done(function(response) {
response.forEach(el => {
console.log(`el.quotes`);
// or if you want to be more specific console.log(`el.quotes.url`);
});
});
}
loadQuotes();
});
If these are nested objects, just append fooBar.
For example change the .done part to:
.done(function(response) {
let qqq = response.quotes
quotes.forEach(el => {
console.log(`el.quotes`);
// or if you want to be more specific console.log(`el.quotes.url`);
});

Parsing array of data and sending with nodemailer?

I've got an array of data that I want to send in a table using NodeMailer that looks something like:
var results = [ {
asin: 'B01571L1Z4',
url: 'domain.com',
favourite: false,
createdAt: 2016-11-18T19:08:41.662Z,
updatedAt: 2016-11-18T19:08:41.662Z,
id: '582f51b94581a7f21a884f40'
},
{
asin: 'B01IM0K0R2',
url: 'domain2.com',
favourite: false,
createdAt: 2016-11-16T17:56:21.696Z,
updatedAt: 2016-11-16T17:56:21.696Z,
id: 'B01IM0K0R2'
}]
What I am trying to do i to create a loop inside my HTML and then loop through the data. I did try the below, but it seems there are limitations on what I can do.
var sendUpdatedMerch = transporter.templateSender({
from: '"Test" <domain1#gmail.com>', // sender address
subject: 'Test Updates', // Subject line
html: '<div><table><thead><tr><th>ASIN</th><th>Url</th><th>Favourite</th><th>createdAt</th></tr></thead><tbody>{{result.forEach((item) => {<tr><td>{{asin}}</a></td><td>{{url}</td><td>{{favourite}}</td><td>{{createdAt}}</td></tr>})}}</tbody></table></div>' // html body
});
sendUpdatedMerch({
to: 'domain#gmail.com'
}, {results}, function(err, info){
if(err){
console.log(err);
} else {
console.log('Done');
}
})
Could anyone point out where I am going wrong please and what I need to do to correct my problems.
It seems you have tried to use results.forEach((item) but you placed this inside the quotes 'result.forEach((item)' which is a string and won't execute at all.
You may have used this kind of syntax in your page when you used the view engines like jade, swig etc which will do the parsing for you. But here, you should call them manually to parse this kind of syntax.
Otherwise, you can do the parsing with the array function as below where I have used array.reduce which is handy and will do the parsing nicely.
You can try the same to generate the content and append it to the html as below.
html: '<div><table><thead><tr><th>ASIN</th><th>Url</th><th>Favourite</th><th>createdAt</th></tr></thead><tbody>' +
content + '</tbody></table></div>' // html body
var results = [ {
asin: 'B01571L1Z4',
url: 'domain.com',
favourite: false,
createdAt: '2016-11-18T19:08:41.662Z',
updatedAt: '2016-11-18T19:08:41.662Z',
id: '582f51b94581a7f21a884f40'
},
{
asin: 'B01IM0K0R2',
url: 'domain2.com',
favourite: false,
createdAt: '2016-11-16T17:56:21.696Z',
updatedAt: '2016-11-16T17:56:21.696Z',
id: 'B01IM0K0R2'
}];
var content = results.reduce(function(a, b) {
return a + '<tr><td>' + b.asin + '</a></td><td>' + b.url + '</td><td>' + b.favourite + '</td><td>' + b.reatedAt + '</td></tr>';
}, '');
console.log(content);
/*
var sendUpdatedMerch = transporter.templateSender({
from: '"Test" <domain1#gmail.com>', // sender address
subject: 'Test Updates', // Subject line
html: '<div><table><thead><tr><th>ASIN</th><th>Url</th><th>Favourite</th><th>createdAt</th></tr></thead><tbody>' + content + '</tbody></table></div>' // html body
});
sendUpdatedMerch({
to: 'domain#gmail.com'
}, {results}, function(err, info){
if(err){
console.log(err);
} else {
console.log('Done');
}
})
*/

update parameters variable on change.search using bootgrid with structured-filter

I am using https://github.com/evoluteur/structured-filter and http://www.jquery-bootgrid.com/ to create an advanced search through ajax/php.
Initially the code works and returns the data from the php file, but when trying to use structured-filter to pass $_GET variables to the php file through the use of jquery-bootgrid I am struggling.
No matter what I try, the url it is posting to has no $_GET variables, I have tried $("#grid-data").bootgrid("reload"); but nothing changes.
It appears the params variable is just not updating.
Here is my jquery script in full:
<script type="text/javascript">
$(document).ready(function() {
$("#myFilter").structFilter({
fields: [{
type: "text",
id: "gamertag",
label: "Gamertag"
}, {
type: "text",
id: "name",
label: "Team Name"
}, {
type: "number",
id: "wagePerMatch",
label: "Wage Per Match"
}, {
type: "number",
id: "gamesRemaining",
label: "Contract Games Remanining"
}, {
type: "boolean",
id: "transferListed",
label: "Transfer Listed"
}
]
});
var params = "";
$("#myFilter").on("change.search", function(event) {
var params = $("#myFilter").structFilter("valUrl");
$("#grid-data").bootgrid("reload");
console.log(params); // works, returns params
});
$("#grid-data").bootgrid({
ajax: true,
url: function() {
return "/api/search.php?" + params; // params never updates?
}
});
});
</script>
Is there a way to update params in .bootgrid when it changes in $("#myFilter").on("change.search" as right now its only sending requests to /api/search.php? (missing the parameters)
Now i don't have to much reputation, i am unable to add comment on this,
Please check this below URL, hope this will help you
http://www.jquery-bootgrid.com/Documentation#events
if you are looking for append the rows in existing grid so you can use "append" as given in URL or if you want to update the whole table you can destory the table and re-create a "bootgrid" object with binding with the respective DOM id's

Adding keys to objects in a parse object

Im working with the parse javascript sdk and i want to add a key to an object in a Parse 'object' when saving it.
For ex:
var saveGif = new SaveGifTags();
saveGif.save({
type: req.body.type,
tag: req.body.tags[i],
gifObjects: newGif
}, {
success: function(data) {
console.log(data);
res.json(data);
},
error: function(data) {
console.log(data);
}
});
gifObjects is my object in the Parse Class. I tried to do something like this
gifObjects: gifOjects[gifObj.id] = newGif;
newGif of course is the object i want to save. This gave me an error of gifObjects is not defined. So i tried something like this
gifObjects[gifObj.id] : newGif;
that didnt work either. i want to create something like this:
{
hgs32: {
url: '',
image: ''
},
64522 : {
url: '',
image: ''
}
}
any suggestions?
Figured it out. Not sure what the downvote is for, but i had to create the object before i saved it.
var gifObjects = {};
gifObjects[gifObj.id] = newGif;
and then the save
saveGif.save({
type: req.body.type,
tag: req.body.tags[i],
gifObjects: gifObjects
},

Categories