jQuery getJSON parsing an array of dicts and flling a table - javascript

I have the following jQuery code in my page:
$('#submit').click(function() {
var $table = $('#search_body');
$.getJSON("/search_issues/" + $("#folders").val(), function(data) {
$.each(data, function(index, dict) {
alert ('each index ' + index);
$.each(obj, function(key, value){
alert('each key ' + key + ':' + value);
$table.innerHTML="<tr><td>" + key + ':' + value + "</td></tr>";
});
});
});
});
In the HTML markup, I have a table defined and the body of the table is defined as
<tbody id="search_body">
</tbody>
I put the two alert statements in the code, and it turns out, the first alert only pops up once, telling me index is 0.
If however, I point my browser to the url that is generated for the call to getJSON, I get an array of 9 objects.
This leads me to believe that my syntax in the inner (or possibly the outer) loop is incorrect. So, I went to an online lint form, and it said that I had no syntax errors, so it looks like a logic error.
BTW, $('#folders') does have a valid value (it's a dropdown and it has been selected)
Thanks
The objects returned when I point my browser is this:
[
{
planning: 0,
id: "0e1a9dba-8bfe-4316-8923-b76f76da3171",
rank: 0,
title: "Test Issue 4"
},
{
planning: 0,
id: "16ef48ab-1257-4fe4-a4ea-bb2a4b2757f6",
rank: 0,
title: "Test Issue 3"
},
{
planning: 0,
id: "4086f816-57dd-49e7-91a4-ef2ac9573555",
rank: 0,
title: "Test Issue 1"
},
{
planning: 0,
id: "45c598f0-fd6a-48d6-9822-1ca8b0a5af4b",
rank: 0,
title: "Test Issue 2"
},
{
planning: 0,
id: "50a62544-3350-4c78-a9eb-9d79a37846ea",
rank: 0,
title: "Test Issue 4"
},
{
planning: 0,
id: "ae7fa839-1161-4d54-92da-662e6aa35936",
rank: 0,
title: "Test Issue 6"
},
{
planning: 0,
id: "c4016338-a766-46ba-a651-3879a844f141",
rank: 0,
title: "Test creating an issue"
},
{
planning: 0,
id: "d9f38b4f-d4ef-4abf-ab30-d511c0082df1",
rank: 0,
title: "Test Issue 5"
}
]

I am changing your code a little bit assuming that this is the desired output:
$('#submit').click(function() {
var $table = $('#search_body');
$.getJSON("/search_issues/" + $("#folders").val(), function(data) {
$.each(data, function(index, dict) {
var $tr = $("<tr></tr>").appendTo($table);
$.each(dict, function(key, value){
$tr.append("<td>" + key + ': ' + value + "</td>");
});
});
});
});

obj does not appear defined ? Try substituting
$.each(dict, function(key, value){
for
$.each(obj, function(key, value){
Also substituting
$table[0].innerHTML += "<tr><td>" + key + ':' + value + "</td></tr>";
for
$table.innerHTML="<tr><td>" + key + ':' + value + "</td></tr>";
to concatenate innerHTML of $table; $table[0] being DOM element having property .innerHTML ; $table being jQuery object not having method .innerHTML
var data = [
{
planning: 0,
id: "0e1a9dba-8bfe-4316-8923-b76f76da3171",
rank: 0,
title: "Test Issue 4"
},
{
planning: 0,
id: "16ef48ab-1257-4fe4-a4ea-bb2a4b2757f6",
rank: 0,
title: "Test Issue 3"
},
{
planning: 0,
id: "4086f816-57dd-49e7-91a4-ef2ac9573555",
rank: 0,
title: "Test Issue 1"
},
{
planning: 0,
id: "45c598f0-fd6a-48d6-9822-1ca8b0a5af4b",
rank: 0,
title: "Test Issue 2"
},
{
planning: 0,
id: "50a62544-3350-4c78-a9eb-9d79a37846ea",
rank: 0,
title: "Test Issue 4"
},
{
planning: 0,
id: "ae7fa839-1161-4d54-92da-662e6aa35936",
rank: 0,
title: "Test Issue 6"
},
{
planning: 0,
id: "c4016338-a766-46ba-a651-3879a844f141",
rank: 0,
title: "Test creating an issue"
},
{
planning: 0,
id: "d9f38b4f-d4ef-4abf-ab30-d511c0082df1",
rank: 0,
title: "Test Issue 5"
}
];
var $table = $('#search_body');
// $.getJSON("/search_issues/" + $("#folders").val(), function(data) {
$.each(data, function(index, dict) {
alert ('each index ' + index);
$.each(dict, function(key, value){
alert('each key ' + key + ':' + value);
$table[0].innerHTML += "<tr><td>" + key + ':' + value + "</td></tr>";
});
});
// });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody id="search_body">
</tbody>
</table>

Related

Need Some help to refactor or optimize the code in javascript object

I have tried writing the array of objects using ternary but still I am thinking to refactor the common properties between them if someone could help me with this would be helpful.
const{address } = A
data: conditionalValue ? [
{ text: text },
{ building: address },
{ ' ': pincode }
]:
[
{ text: text },
{ building: address },
{ ' ': pincode },
{ 'somevalue': someValue1 },
{ ' ': otherValue},
],
still the { text: text },{ building: address },{ ' ': pincode } objects are same between 2 condition
You can use some destructuring on a array of additional values:
const conditionalValue = false;
const data = [
{ text: 'text' },
{ building: 'address' },
{ ' ': 'pincode' },
...(
conditionalValue
? [{ 'somevalue': 'someValue1' },{ ' ': 'otherValue'}]
: []
)
];
console.log(data);
However, I think it might be cleaner to just push your other values into the data array.

How can i display massages based on the user who sent and received the message

I don't know what's wrong with my code am not getting the intended output. Anybody to lend a helping hand and I'll really appreciate it.
If append the row class inside the for loop am getting all the messages but you can't differentiate who sent and who received and when I append the class outside the for loop am only getting one message.
xhr.onload = function () {
var messages = [
{ id: 36, message: "hay here", username: null, senderId: 1, receiverId: 9 },
{ id: 38, message: "hay there again", username: null, senderId: 1, receiverId: 9 },
{ id: 37, message: "yes hay", username: null, senderId: 9, receiverId: 1 },
];
var rowClass = "";
for (var message = 0; message < messages.length; message++) {
if (messages[message].senderId === messages[message].senderId) {
rowClass =
'<div style="text-align:right">' +
'<p style="background-color:lightblue">' +
mymessages[message].message +
"</p>" +
"<div>";
} else {
rowClass =
'<div style="text-align:left">' + '<p style="background-color:green">';
messages[message].message;
"</p>" + "<div>";
}
}
$(".message").append(rowClass);
};
You need to check whether the current user's id is same as that of the message, for example:
const currentUserId = 9;
var messages = [
{ id: 36, message: "hay here", username: null, senderId: 1, receiverId: 9 },
{ id: 38, message: "hay there again", username: null, senderId: 1, receiverId: 9 },
{ id: 37, message: "yes hay", username: null, senderId: 9, receiverId: 1 },
];
var rowClass = "";
for (var message = 0; message < messages.length; message++) {
if (messages[message].senderId === currentUserId) {
rowClass +=
'<div style="text-align:right">' +
'<p style="background-color:lightblue">' +
messages[message].message +
"</p>" +
"<div>";
} else {
rowClass +=
'<div style="text-align:left">' +
'<p style="background-color:green">' +
messages[message].message +
"</p>" +
"<div>";
}
}
$(".message").append(rowClass);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="message"></div>

How would I each through dynamic content and append something if a value = false?

I'm trying to iterate over some JSON that I have included in my file and everything seems to be working fine up until I want to add my icons into each stakebox icon div. Any idea what might be going wrong? I want to add one icon if the value of my JSON object === true and one if the value === false.
$.each(stakeBox, function (i, stakeBoxData) {
var jsonDate = stakeBoxData.data_change_date;
var winLoss = stakeBoxData.win;
var points = stakeBoxData.amount_stakebox;
var winLoss = stakeBoxData.win;
var id = stakeBoxData.id;
if (stakeBoxDay < jsonDate) {
var self = $(this);
console.log(this.win);
$('.stakebox-container').append('\
<div id="' + id + '" class="stakebox-message-container">\
<div id="stakebox-icon"></div>\
<div><h5 id="stakebox-game"></h5></div>\
<div><h5 id="stakebox-points">' + points + '</h5></div>\
</div>\
');
if (this.win === true) {
$('#stakebox-icon').append('<i class="far fa-smile face"></i>');
} else {
$('.stakebox-message-container').css('background', '#a20000');
$('#stakebox-icon').append('<i class="far fa-frown face"></i>');
};
// console.log(i);
} else {
// console.log('nope');
}
});
Here is some of the JSON for reference:
var stakeBox = [{
id: "1",
amount: "40.00",
user_id: "1",
amount_stakebox: "33",
win: true,
data_change_date: "20180229",
username: "bkessler",
game_id: "1380",
team_id: "791",
status: "1"
}, {
id: "2",
amount: "1.00",
user_id: "1",
amount_stakebox: "4124124",
win: false,
data_change_date: "20180429",
username: "bkessler",
game_id: "1380",
team_id: "791",
status: "1"
}];

x-editable custom fields cannot get text of select menu

Ive followed this example from another SO thread:
X-editable custom field type not respecting overridden defaults
and its helped me to create a similar custom field with x-editable. All is working ok but i cant figure out how render/display the 'text' of the select - the SO example ouputs the 'value'. my js to initialis the x-editable to use my custom inputs is thus:
$('#stffulladdress').editable({
url : '',
pk : 6,
value : {
address : "",
city : "",
region : "",
postcode : "",
country : "eng"
},
sourceCountry: [
{ value: "eng", text: "ENGLAND" },
{ value: "ire", text: "IRELAND" },
{ value: "sco", text: "SCOTLAND" },
{ value: "cym", text: "WALES" }
],
validate : function(value) {
if (value.address == '' || value.postcode == '') return "Address first lines AND Postcode required";
},
display : function(value) {
if (!value) {
$(this).empty();
return;
}
console.log(value.country);
var html = $('<div>').html( value.address + '<br />' + value.city + '<br />' + value.region + '<br />' + value.postcode + '<br />' + value.country );
$(this).html(html);
}
});
My custom x-editable class is the same as the SO example mentioned with the only difference being i have more inputs -they work ok as expected. I would have thought that this snippet from the x-edit class gets the text of the selected item:
value2html: function(value, element) {
if(!value) {
$(element).empty();
return;
}
var countryText = value.country;
$.each(this.sourceCountryData, function (i, v) {
if (v.value == countryText) {
countryText = v.text.toUpperCase();
}
});
var html = $('<div>').html( value.address + ',<br />' + value.city + ',<br />' + value.region + ',<br />' + value.postcode + ',<br />' + countryText );
$(element).html(html);
},
But upn displaying the selected country i still get the country value "eng" and not the text "England".
I've tried :
value.country which gives me the value 'eng'
and value.text gives undefined
Any idea how i can get the selected text??
thanks
Try the sourceCountry as follow:
sourceCountry: [
{ "eng": "ENGLAND" },
{ "ire": "IRELAND" },
{ "sco": "SCOTLAND" },
{ "cym": "WALES" }
],

Parse Database JavaScript and PhoneGap

I've been working on an restaurant app that should get the menu from an online database.
This is how I currently and "Manually" populate the menu:
Controller.html
$scope.menu = [{
name: 'Espresso',
price: 27,
qty: 1,
desc: "One shot of espresso prepared with 7 grams of ground coffee in a single portafilter. The shot should be 1 ounce of liquid. You have two choices with espresso: ristretto, a very short or “restrained” shot, brewed at less than 2/3 of a demitasse, or luongo, a long pull of espresso brewed so the liquid should be more than 2/3 of a demitasse.",
img: "img/espresso.png",
active: false,
sizes: [{name: "Small", price: 0, active:false},
{name: "Medium", price: 5, active:false},
{name: "Large", price: 10, active:false}],
flavors: [{name: 'Vanilla', price: 8, active: false},
{name: 'Almond', price: 8, active: false},
{name: 'Hazelnut', price: 8, active: false},
{name: 'Caramel', price: 8, active: false}]
}];
However I can't seem to achieve populating this using Parse, how would I approach this using a query as the following (Which is a working query).
Index.html
<script type="text/javascript">
Parse.initialize("vGoJDvwwfZBiUFcwfkee7M5vCqL7lLxCgKIFJXDc", "6VRlos6qppaek1uDPPLqpHtmB3fHefOJMqYJNxj9");
var DrinkMenu = Parse.Object.extend("DrinkMenu");
var query = new Parse.Query(DrinkMenu);
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " items.");
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
alert(object.id + ' - ' + object.get('name'));
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
</script>
You can notice I can get the variables needed for each item, in this case the name of the first result, which I display in an alert.
Any help is appreciated!
After Parse.initialize, create a variable, like this:
var arrMenu = [];
then change the line alert(object.id + ' - ' + object.get('name')); to
arrMenu.push({
name: object.get('name'),
price: object.get('price'),
qty: object.get('qty'),
desc: object.get('desc'),
img: object.get('img'),
active: object.get('active'),
sizes: object.get('sizes'),
flavors: object.get('flavor')
});
I am supposing that you are storing the info in the Parse Collection with the structure you mentioned. If it is different, let me know.
And, after the brack the closes the for, you add:
$scope.menu = arrMenu;
I hope it helps!

Categories

Resources