DataTables: Adding new row Requested unknown parameter 'id' for row 14 - javascript

AJAX:
{
"data": [
{
"id": 1,
"name": "Dashboard",
"url": "/",
"icon": "icon-home",
"child_of": null,
"show": 1,
"admin": 0
},
{
"id": 2,
"name": "Submenu 3",
"url": "http://stackoverflow.com",
"icon": null,
"child_of": null,
"show": 1,
"admin": 0
},
]
}
JS:
$('#table-editable').dataTable({
"ajax": {
"url": "/api/menu",
"type": "GET",
},
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "url" },
{ "data": "icon" },
{ "data": "child_of" },
{ "data": "show" },
{ "data": "admin" }
]
});
So I'm using AJAX to fill up data in tables. It is working.
I am using this: DataTables: Inline Editing for creating new row. (Check Adding row & Edit Mode in link)
Problem:
Consider I've 13 rows. So IDs will be 1, 2, 3... 13.
While creating new row:
It does this: oTable.fnAddData('', '',....);
So when I add new row, it gives me error:
DataTables warning: table id=table-editable - Requested unknown parameter 'id' for row 14. For more information about this error, please see datatables.net/tn/4
So, basically it tries to fetch row id 14. But, there's no row with id 14.
So what is the solution?

var data = [
{
"CategoryID": 1,
"CategoryName": "Soler Power Plant",
"CategoryProducts": [
{
"ID": 1,
"Name": 'Commercial Solar Power Plant',
"SubTitle": 'Eco, Eco Friendly, Energy, Green, Solar',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": 'Having a pre-determined quality administration system, we are thoroughly involved in delivering Commercial Solar Power Plant.',
"ImageUrl": 'assets/images/Products/Sola-power-plant.jpg',
},
{
"ID": 2,
"Name": 'Industrial Solar Power Plants',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": 'So as to become a preferential business name, we are thoroughly engrossed in shipping an inclusive collection of Industrial Solar Power Plants.',
"ImageUrl": 'assets/images/Products/Industrial_Solar_Power_Plants.jpg',
},
{
"ID": 3,
"Name": 'On Grid Solar Plant',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 1.1 Lakh / Unit',
"Body_Material": '',
"Description": "We are the leading firm of On Grid Solar Plant. To sustain the quality, our products are made under the guidance of industry certified professionals.",
"ImageUrl": 'assets/images/Products/On_Grid_Solar_Plant.jpg',
},
{
"ID": 4,
"Name": 'On Grid Solar Power Plant',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": "We are the leading firm of On Grid Solar Power Plant. To sustain the quality, our products are made under the guidance of industry top professionals.",
"ImageUrl": 'assets/images/Products/On_Grid_Solar_Power_Plant.jpg',
},
{
"ID": 5,
"Name": 'Solar Power Plant',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": "We are the leading firm of Solar Power Plant. To sustain the quality, our products are made under the guidance of industry certified professionals.",
"ImageUrl": 'assets/images/Products/Solar_Power_Plant.jpg',
},
]
}
]
function GetProducts() {
var products = data;
$.each(products, function () {
//var product = products.filter(filterByID)
var product = this;
$('#ProductDetails').append('<h2 class="text-center">' + this.CategoryName + '</h2>');
var details = product;
$.each(details.CategoryProducts, function () {
tempData = tempData + '<div class="col-md-4 col-sm-6">' +
'<div class="project-box">' +
'<div class="frame-outer">' +
'<div class="frame">' +
'<img style="width:350px;" src="' + this.ImageUrl + '" class="attachment-340x220 size-340x220 wp-post-image" alt="">' +
'</div>' +
'</div>' +
'<div class="text-box">' +
'<h3><a>' + this.Name + '</a></h3>' +
'<div class="tags-row">' +
'<a class="link">' + this.SubTitle + '</a>' +
'</div>' +
'<p>' + this.Description + '</p>' +
//'More Details' +
'</div>' +
'</div>' +
'</div>';
});
$('#ProductDetails').append('<div class="row">' + tempData + '</div>');
tempData = '';
});
}
Here, it's my own code may be it's help you

Related

Avoid Iterating Outer Loop

I've a scenario where I've to iterate two list or arrays to get required values. So I am doing something like this:
var html = "";
$.each(list, function (i, set1) { //set1 is a list or array
$.each(set1.Tabs, function (i, set2) { //set1.Tabs is another one
html += "<li><a href='#" + set2.TabName + "'>" + set2.Details + "</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>";
})
})
The above works fine, it returns me the required data. But the problem is, say the outer loop has 10 values and the inner loop has four values. So the inner loop gets iterated ten times with the four values. This is natural and it should do. I was trying to get distinct values using the following (For the outer loop specifically):
list = list.filter((x, i, a) => a.indexOf(x) === i);
Though the above should work, my expected output is as follows:
Input: [1, 2, 3, 3, 4, 5, 6, 6]
Output: [1, 2, 3, 4, 5, 6]
N.B: My concern is with the inner loop, not with the outer one. But to iterate the inner loop, I've to go through the outer loop. Is there any way I can get the inner loop work directly?
Update 1: Sample Code
$(document).ready(function() {
var html = "";
var data = [{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" }
]
},
{
"id": "0002",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" }
]
}
]
$.each(data, function(i, set1) { //set1 is a list or array
$.each(set1.topping, function(i, set2) { //set1.Tabs is another one
html += "<li><a href='#" + set2.id + "'>" + set2.type + "</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>";
})
})
$('#add').append(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="add"></div>
You can create unique toppings based on the id and then render the list using unique toppings. To create unique toppings, you can use flatMap() Object.values() and array#reduce.
$(document).ready(function() {
var html = "";
var data = [{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"topping": [{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
{
"id": "5005",
"type": "Sugar"
},
{
"id": "5007",
"type": "Powdered Sugar"
}
]
},
{
"id": "0002",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"topping": [{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
{
"id": "5005",
"type": "Sugar"
},
{
"id": "5007",
"type": "Powdered Sugar"
}
]
}
]
const uniqueToppings = Object.values(data
.flatMap(o => o.topping)
.reduce((r, {id, type}) => {
r[id] = r[id] || {id, type};
return r;
},{}));;
$.each(uniqueToppings, function(i, set) {
html += "<li><a href='#" + set.id + "'>" + set.type + "</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>";
});
$('#add').append(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="add"></div>

Javascript Not Displaying Button Text

full json is
{
"id": "70dec1ac-345f-4b94-b255-b09c5ab1b522",
"name": "card",
"auto": true,
"contexts": [],
"responses": [
{
"resetContexts": false,
"affectedContexts": [],
"parameters": [],
"messages": [
{
"type": 1,
"platform": "facebook",
"title": "this is the title updated",
"subtitle": "this is the subtitle",
"imageUrl": "https://www.gettyimages.ie/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg",
"buttons": [
{
"text": "this is the button"
},
{
"text": "this is also a button"
}
],
"lang": "en"
},
{
"type": 0,
"speech": []
}
],
"defaultResponsePlatforms": {},
"speech": []
}
],
"priority": 500000,
"cortanaCommand": {
"navigateOrService": "NAVIGATE",
"target": ""
},
"webhookUsed": false,
"webhookForSlotFilling": false,
"lastUpdate": 1530197695,
"fallbackIntent": false,
"events": [],
"userSays": [
{
"id": "528c22d4-49d7-4ab9-a8db-fcd84d57694b",
"data": [
{
"text": "card"
}
],
"isTemplate": false,
"count": 0,
"updated": 1530196620,
"isAuto": false
}
],
"followUpIntents": [],
"templates": []
}
I am actually making a chatbot for wordpress to communicate with api.ai or dialogflow
The code I am currently using to display a card is the following:
var html = "<div class=\"myc-conversation-bubble myc-conversation-response myc-is-active myc-image-response\"><img src=\"" + imageUrl + "\"/></div>";
html+="<div class=\"myc-card-title\">" + title + "</div>"
html += "<div class=\"myc-card-subtitle\">" + subtitle+ "</div>";
html += "<input type=\"button\" " + "style=\"background-color:rgb(221, 153, 51);text-transform: none\"" + "class=\"myc-quick-reply\" value=\"" +buttons[0]+ "\" />";
var innerHTML = "<div class=\"myc-conversation-bubble-container myc-conversation-bubble-container-response\"><div class=\"myc-conversation-bubble myc-conversation-response myc-is-active myc-quick-replies-response\">" + html + "</div>";
I am getting the image ,title ,subtitle correctly but the Button is displayed as [object Object] what is the correct way to do it?
The button text is in the text property.
Try to replace buttons[0] with buttons[0].text.
in your case buttons is an array of object and have property text. so try buttons[0].text

Show JSON by clicking a button

How can I show the JSON object that is in the random by clicking the button. With Javascript.
var myObject = {
"catalogo": [
{
"id" : "001",
"name":"Nike",
"desc" : "shoes",
"price": 500,
},
{
"id" : "002",
"name":"MIKEY",
"desc" : "shoes",
"price": 500,
},
{
"id" : "003",
"name":"VANS",
"desc" : "shoes",
"price": 500,
},
{
"id" : "004",
"name":"SPORT",
"desc" : "shoes",
"price": 500,
}
]
};
var random = myObject.catalogo[Math.floor(Math.random()* myObject.catalogo.length)];
document.getElementById('table').innerHTML = random.shortname + "<br>" + "$" + random.price + ".00";
HTML CODE:
Here is the code for the button to display the value.
<div>
<div id="random"></div>
<button>Añadir</button>
</div>
I want to show it here
<div>
<p class="line"></p>
</div>
This is how you would do it.
Take note, you also had some errors in your logic for getting the random data. The table ID doesn't exist (changed to line) and shortname isn't in your data (changed to name)
var myObject = {
"catalogo": [{
"id": "001",
"name": "Nike",
"desc": "shoes",
"price": 500,
},
{
"id": "002",
"name": "MIKEY",
"desc": "shoes",
"price": 500,
},
{
"id": "003",
"name": "VANS",
"desc": "shoes",
"price": 500,
},
{
"id": "004",
"name": "SPORT",
"desc": "shoes",
"price": 500,
}
]
};
function showRandom() {
var random = myObject.catalogo[Math.floor(Math.random() * myObject.catalogo.length)];
document.querySelector('.line').innerHTML = random.name + "<br>" + "$" + random.price + ".00";
}
<div>
<div id="random"></div>
<button onclick="showRandom()">Añadir</button>
</div>
<div>
<p class="line"></p>
</div>
Change your button to <button id="anadir">Añadir</button>.
After doing this, you can get your button from JS after the document loads:
window.addEventListener("DOMContentLoaded", function(event) {
var myAddButtton = document.getElementById('anadir');
myAddButton.onclick = function() {
var random = myObject.catalogo[
Math.floor(Math.random()* myObject.catalogo.length)
];
document.querySelector('.line')
.innerHTML = random.shortname + "<br>" + "$" + random.price + ".00";
}
}
Load this in a <script> tag in your page and it should work.

How to reset data sort to original sort

Am working on an existing site where there seems to be a use the DataFilters jQuery Plugin where data is sorted by lowest price and highest price. For reasons outside my control, I can't edit the original code and there is a requirement to add a link when clicked it will reset the sort to its original state prior to the sort.
Thanks for your help
UPDATE: I got access to DataFilter initialisation code similar to what's here: http://www.datafilters.info/config.php
UPDATE: I got access to the DataFilter initialisation code which I can update
$(document).ready(function() {
$("#filterControls").show();
initFilters();
});
function initFilters() {
function freeTextSearchExtractText(element) {
return element.find('.brand').text() + " " + element.find('.model').text() + " " + element.find('.stock').text() + " " + element.find('.os').text();
}
var sortBy = [
{"heading": "Price (low-high)", "id": "cost", "direction": "1"},
{"heading": "Price (high-low)", "id": "cost", "direction": "-1"},
{"heading": "Brand (A-Z)", "id": "brand", "direction": "1"},
{"heading": "Brand (Z-A)", "id": "brand", "direction": "-1"}
]
$('#handsetList').DataFilter('init', {
"filters": [
{"id":"cost", "dataType":"currency", "filterType":"sortOnly"},
{"heading": "Brand", "id": "brand", "dataType": "default", "filterType": "checkboxes" },
{"heading": "4G readiness", "id": "tariffType", "dataType": "default", "filterType": "checkboxes", "hideSingleItem": "true" },
{"heading": "Refurbished", "id": "model", "dataType": "default", "filterType": "checkboxes", "items": ["~Refurb"] },
{"heading": "Stock status", "id": "stock", "dataType": "stock", "filterType": "checkboxes" },
{"heading": "Operating system", "id": "os", "dataType": "default", "filterType": "checkboxes"}
],
"pageSize": 9,
"useFreeTextSearch": true,
"freeTextSearchHeading": "Search phones",
"freeTextSearchExtractTextFn": freeTextSearchExtractText,
"sortingDropDown": sortBy,
"sortingDropDownHeading": "Sort phones",
"onSuccess": onSuccessFnDesktop,
"useLoadingOverlayOnFilterIfSlow": true,
"slowTimeMs": 300,
"hashNavigationEnabled": true
});
var checkVisible = setInterval(function() {
if($('.filterWrapper').length == 0 || !$('.filterWrapper').is(':visible')) return;
clearInterval(checkVisible);
merchandisedFilters();
}, 300);
}

How to access nested value from JSON Instagram API with Javascript

Im trying to modify script from https://github.com/bigflannel/bigflannel-Instafeed to access Instagram Photos in Website. But it doesn't include feature to display photo comments. So, im trying to modify but it returns undefined value. The script uses javascript to access data from API.
Example:
[
{
"attribution": null,
"tags": [
],
"type": "image",
"location": null,
"comments": {
"count": 2,
"data": [
{
"created_time": "1389168592",
"text": "Beautiful bridge!",
"from": {
"username": "realwahyuputra",
"profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/profile_180213154_75sq_1359089013.jpg",
"id": "180213154",
"full_name": "realwahyuputra"
},
"id": "628714182443349004"
},
{
"created_time": "1389168601",
"text": "also good views",
"from": {
"username": "realwahyuputra",
"profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/profile_180213154_75sq_1359089013.jpg",
"id": "180213154",
"full_name": "realwahyuputra"
},
"id": "628714254652486672"
}
]
},
"filter": "Hefe",
"created_time": "1350749506",
"link": "http:\/\/instagram.com\/p\/RAqdlGyTSc\/",
"likes": {
"count": 0,
"data": [
]
},
"images": {
"low_resolution": {
"url": "http:\/\/distilleryimage0.s3.amazonaws.com\/d87203101ad011e297b922000a1fa527_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http:\/\/distilleryimage0.s3.amazonaws.com\/d87203101ad011e297b922000a1fa527_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http:\/\/distilleryimage0.s3.amazonaws.com\/d87203101ad011e297b922000a1fa527_7.jpg",
"width": 612,
"height": 612
}
},
"users_in_photo": [
],
"caption": {
"created_time": "1350749545",
"text": "From the office",
"from": {
"username": "bigflannel",
"profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/anonymousUser.jpg",
"id": "240129684",
"full_name": "Mike Hartley"
},
"id": "306431853609956969"
},
"user_has_liked": false,
"id": "306431525321782428_240129684",
"user": {
"username": "bigflannel",
"website": "",
"profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/anonymousUser.jpg",
"full_name": "Mike Hartley",
"bio": "",
"id": "240129684"
}
}];
Here's one of function to access data from that JSON:
function imageCaptionText(timestamp) {
var text = 'Filter: ' + imageData[imageCount].filter + '<br />'
if (imageData[imageCount].caption != null) {
text = text + 'Caption: ' + imageData[imageCount].caption.text + '<br />';
}
if (imageData[imageCount].likes.count > 0) {
text = text + 'Likes: ' + imageData[imageCount].likes.count + '<br />';
}
if (imageData[imageCount].comments.count > 0) {
text = text + 'Comments: ' + imageData[imageCount].comments.count + '<br />';
}
if (imageData[imageCount].comments.data != null) {
text = text + 'Comments Data: ' + imageData[imageCount].comments.data.text + '<br />';
}
if (imageData[imageCount].location != null) {
text = text + 'Location: ' + imageData[imageCount].location + '<br />';
}
var date = new Date(1000*timestamp);
text = text + 'Date: ' + date.toLocaleString() + '<br />';
text = text + 'On Instagram<br />';
return text; }
Everything goes fine except this code returns undefined value (I'm trying to create this to access comments data)
if (imageData[imageCount].comments.data != null) {
text = text + 'Comments Data: ' + imageData[imageCount].comments.data.text + '<br />';
}
How to make it works? Any help would be appreciated. Thanks :)
comments.data is an array, the actual text will be at imageData[imageCount].comments.data[commentCount].text so you have to do something like this:
if (imageData[imageCount].comments.data != null) {
text = 'Comments Data:<br />';
imageData[imageCount].comments.data.forEach(function(comment){
text += comment.from.username + ': ' + comment.text + '<br />';
});
}

Categories

Resources