Add Property dynamically to the JSON array - javascript

I would like to two add property Id and ButtonId to the exisiting json result. I have pasted the below js code for reference and I would like to pass the jsonresult to MVC controller. As of now it returns null. please help to proceed. Thanks.
my final result should look like this
json{"Groups":{"Id":"2","ButtonId":"1142","1186","1189"},
{"Id":"3","ButtonId":"1171","1173","1174","1175","1176","1187"},
{"Id":"4","ButtonId":"1177","1178","1179"}} etc..
var btnlist = {Groups: {Id:"", ButtonId: ""}};
$.each($(".buttonData"), function (index, value) {
var values = value.id.split(':');
grpid = values[0].split('-')[1];
btnid = values[1].split('-')[1];
console.log('grpid=' + grpid + ' btnid=' + btnid);
if (typeof (btnlist['Groups'][grpid]) == 'undefined') {
btnlist['Groups'][grpid] = [];
}
btnlist['Groups'][grpid].push(btnid);
});
$.ajax({
type: "POST",
url: "#Url.Action("Home", "Menu")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(btnlist) ,
success: function (result) {
console.log('json' + JSON.stringify(btnlist));
console.debug(result);
},
error: function (request, error) {
console.debug(error);
}
});
This is the json result before pushing into the multidimensional array
The json result, where the properties Id and ButtonId is inserted behind.
null result passed to the controller

With assistance of my colleague, the desired output is as below. This is for other programmers who face similar issue with JSON array. Thanks.
var btnlist = [];
btngrps = $('.btn-sort-container');
$.each(btngrps, function(k, v) {
btnarr = {};
gid = $(this).attr('id');
grpid = gid.split('-')[1];
btnarr.Id = gid.split('-')[1];
btnobjs = $(v).find('.buttonData');
if (btnobjs.length) {
btnarr['btnId'] = [];
$.each(btnobjs, function(bk, bv) {
btnid = $(bv).attr('id').split('-')[2];
btnarr['btnId'].push($(bv).attr('id').split('-')[2]);
});
console.debug(btnarr);
btnlist.push(btnarr);
}
});
console.debug(btnlist);
Output on console
: http://i.stack.imgur.com/oJ3Dy.png

Related

"Error : Cannot use 'in' operator to search for 'length' in [{"ID":"2","Name":"EAA2"}]" when performing $.each

What ever I do, I keep getting the same error. The only thing I have found that might of helped is the JSON.parse, but I still get the same problem. console log gives data as [{"ID":"2","Name":"EAA2"}]
I split it into two functions as I didn't want to keep going back to the api everytime a user selects/de-selects an option.
I have also tried the following:
Changing vars to lets
Passing data.d from the update to the populate
function populateAvailableAuthorities() {
var list = $('#availableAA');
var data = JSON.parse($('#AAJSON').val());
var auths = $('#tbSelectedAA').val();
list.empty();
$.each(data, function (key, entry) {
if (!~auths.indexOf(entry.ID + ';')) {
list.append($('<option></option>').attr('value', entry.ID).text(entry.Name));
}
});
}
function updateListboxes() {
var teams = '';
let aa = $('#AAJSON');
aa.empty();
$('#cblTeams input:checked').each(function () {
teams += $(this).attr('value') + ',';
});
if (teams.length > 1) {
teams = teams.substr(0, teams.length - 1);
$.ajax({
type: "POST",
url: '<%# ResolveUrl("~/api/Authorities.asmx/FetchByTeam") %>',
data: '{teams: "' + teams + '"}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
aa.val(JSON.stringify(data.d));
populateAvailableAuthorities();
}
});
}
}
It would seem that "over-stringifying" is an issue with JSON. If I doubled the JSON.parse or removed the JSON.stringify it all works correctly.
Annoying!!

How to read data using JSONP, Ajax and jquery?

I am trying to read data from this API, but it is not working, I have an input box where I enter the isbn number and then get the data, using jsonp. Could you possibly help me in identifying where my error("Cannot read property 'title' of undefined") is?
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(isbn){
var infoUrl = isbn.info_url;
var thumbnailUrl = isbn.thumbnail_url;
var title = isbn.details.title;
var publishers = isbn.details.publishers;
var isbn13 = isbn.details.isbn_13;
console.log(isbn.info_url);
}
});
}
Open Library's API expects bibkeys to be prefixed with their type and a colon, rather than just the number alone:
function add(){
var isbn = 'ISBN:' + $("#isbn").val();
// ...
The colon also means the value should be URL-encoded, which jQuery can do for you:
$.ajax({
url: "https://openlibrary.org/api/books?jscmd=details&callback=?",
data: { bidkeys: isbn },
dataType: "jsonp",
Then, the data it returns reuses the bibkeys you provided as properties:
{ "ISBN:0123456789": { "info_url": ..., "details": { ... }, ... } }
To access the book's information, you'll have to first access this property:
success: function(data){
var bookInfo = data[isbn];
console.log(bookInfo.details.title);
// etc.
}
Example: https://jsfiddle.net/3p6s7051/
You can also retrieve the bibkey from the object itself using Object.keys():
success: function (data) {
var bibkey = Object.keys(data)[0];
var bookInfo = data[bibkey];
console.log(bookInfo.details.title);
// ...
}
Note: You can use this to validate, since the request can be technically successful and not include any book information (i.e. no matches found):
success: function (data) {
var bibkeys = Object.keys(data);
if (bibkeys.length === 0)
return showError('No books were found with the ISBN provided.');
// ...
Example: https://jsfiddle.net/q0aqys87/
I asked a professor, and this is how she told me to solve it:
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(data){
var thumb=data["ISBN:"+isbn+""].thumbnail_url;
....
}
});
}

JQuery AutoComplete with JSON Result Not Working

I am using a JQuery autocomplete to display a list of available courses. I am doing a post to get a list of Courses from the server, I manipulate the data to be in the expected format, and I pass it to the autocomplete function. The problem is that it does not work unless I hard copy and paste the values newSource and paste them into source.
The variable newSource = ["Enc1001","ENC1002","Enc1003","ENC1101"....etc].
The ajax post to get the data from the server
//Auto complete for search box
$('#AdditionalSearch').on('input', function () {
var source = [];
var inputValue = $('#AdditionalSearch').val();
if (inputValue !== '') { //the value is not empty, we'll do a post to get the data.
url = "/Course/CourseSearch";
$.ajax({
method: 'POST',
dataType: 'json',
contentType: 'application/json',
cache: false,
data: JSON.stringify({ "searchCourseValue": inputValue }),
url: url,
success: function (data) {
if (data.Ok) {
var myData = JSON.parse(data.data);
var newSource = '[';
$.each(myData.ResultValue, function (index, item) {
if ((myData.ResultValue.length -1) == index)
newSource += '"' + item.Name+'"';
else
newSource += '"'+ item.Name + '",';
});
newSource += "]";
console.log(newSource);
source = newSource;
}
setNameAutoComplete(source);
},
error: function (jqXHR) {
console.log(error);
}
});
} else { //The user either delete all the input or there is nothing in the search box.
//The value is empty, so clear the listbox.
setNameAutoComplete(source);
}
});
//Passing the source to the auto complete function
var setNameAutoComplete = function (data) {
console.log(data);
$('#AdditionalSearch').autocomplete({
source: data
});
}
Is there something that I am missing here?
When you literally paste newSource = ["Enc1001","ENC1002","Enc1003","ENC1101"....etc]in your code, you are building an array object. However, in your success method, you are building a string (the string-representation of that same object). What you want to be doing is build an actual array in stead.
...
success: function (data) {
if (data.Ok) {
var myData = JSON.parse(data.data);
var newSource = [];
$.each(myData.ResultValue, function (index, item) {
newSource.push(item.Name);
});
console.log(newSource);
source = newSource;
}
setNameAutoComplete(source);
},
...

Pass Json Object and String Value at once in Ajax

I want to pass a Json Object and String Value together in ajax call. I have attached my code below.
$('#ddcountryid').change(function () {
var jdata = ko.mapping.toJSON(viewModel);
var Cid = $(this).val();
//alert(intCountry);
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")',
type: 'POST',
data: jdata,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
ko.mapping.fromJS(data, viewModel);
}
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
});
});
My Action Method
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I am getting wrapper object with Values, but how can get the CID as well. Can anyone please help me on this??.
you can pass it as query string parameter:
var Cid = $(this).val();
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")' + '?cID=' + Cid,
...
server side:
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
OR add a new property to your Wrapper object as Gavin Fang suggested:
var Cid = $(this).val();
viewModel.Cid = Cid;
var jdata = ko.mapping.toJSON(viewModel);
server side code:
public JsonResult PopulateDropDown(Wrapper wrapper)
{
var cid = wrapper.Cid;
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I think you can add a property to store you 'CID' to your viewModel.
and you can get the CID in the 'success' function in javascript in here, I think.
You can achieve this is two ways:
You can add extra field for existing json 'jdata' by defining field jdata.cid = null; and assigning it as jdata.cid = $(this).val();.
Prepare an object to hold both json data and string value:
var obj = {"json": jdata, "string":$(this).value()};
then pass obj in data parameter

How to break a Json var into specific formate in jquery

I am retrieving values from database and parsing it into JSON .My JSON data formate is like..
[{"INCOMING":"09:09:49","INETCALL":"00:14:09","ISD":"00:05:50","LOCAL":"02:38:02","STD":"01:39:28"}]
I want to break this JSON value into two variables one is:
var toc=["INCOMING","INETCALL","ISD","LOCAL","STD"]
and the other variable like this..
var callduration=["09:09:49","00:14:09","00:05:50","02:38:0","01:39:28"]
Now as per my need i have to break it into two variables for that i have written a for loop but it is not working .Here is my Client side code..
$.ajax({
type: 'GET',
url: 'getdataduration',
async:false,
dataType: "text",
success: function(data) {
console.log(data);
var dbdata=JSON.parse(data);
console.log(dbdata);
for(var i=0,len=dbdata.length;i<len;i++){
$.isNumeric(dbdata[i]) ? callduration.push(dbdata[i]) : toc.push(dbdata[i]);
}
}
});
console.log(toc);
console.log(callduration);
Please guys help me .
Thanks in advance..
This is how you would work witih that...
var data = [{"INCOMING":"09:09:49","INETCALL":"00:14:09","ISD":"00:05:50","LOCAL":"02:38:02","STD":"01:39:28"}];
console.log(data);
console.log( data[0].INCOMING ); // 09:09:49
console.log( data[0]['INCOMING'] ); // 09:09:49
var keys = Object.keys(data[0]);
console.log(keys); // ["INCOMING", "INETCALL", "ISD", "LOCAL", "STD"]
var values = [];
var keys = [];
$.each(data,function(i,val){
console.log(val); // Object {INCOMING: "09:09:49", INETCALL: "00:14:09", ISD: "00:05:50", LOCAL: "02:38:02", STD: "01:39:28"}
$.each(val,function(key2,val2){
console.log(key2 + " = " + val2);
keys.push(key2);
values.push(val2);
// INCOMING = 09:09:49
// INETCALL = 00:14:09
// ISD = 00:05:50
// LOCAL = 02:38:02
// STD = 01:39:28
});
});
console.log(keys); // ["INCOMING", "INETCALL", "ISD", "LOCAL", "STD"]
console.log(values); // ["09:09:49", "00:14:09", "00:05:50", "02:38:02", "01:39:28"]
Can you try this,
$(function(){
var toc = [];
var callduration =[];
$.ajax({
type: 'GET',
url: 'getdataduration',
async:false,
dataType: "text",
success: function(data) {
// console.log(data);
var dbdata=JSON.parse(data);
// console.log(dbdata);
$.each(dbdata[0], function(key, value){
console.log(key, value);
toc.push(key);
callduration.push(value)
});
}
});
console.log(toc);
console.log(callduration);
});
Output Console:
["INCOMING", "INETCALL", "ISD", "LOCAL", "STD"]
["09:09:49", "00:14:09", "00:05:50", "02:38:02", "01:39:28"]

Categories

Resources