How to break a Json var into specific formate in jquery - javascript

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"]

Related

array is empty even if it was successfully mapped

I'm running into issues with _.map (using underscore.jshttp://underscorejs.org).
getCalories: function() {
var encode = "1%20";
var calSource = "https://api.edamam.com/api/nutrition-data?app_id=#&app_key=#";
_.map(ingArray, function(elem)
{
return $.ajax(calSource, {
dataType: "json",
jsonp: "jsonp",
data: "ingr=" + encode + elem,
complete: function(r) {
var obj = JSON.parse(r.responseText);
var calorie = obj.calories;
calArray.push(calorie);
console.log(calArray);
}
});
});
},
I need to use the latest iteration of calArray in another function. However, it always comes up as undefined. So I inserted a console.log above and this is what I get:
app.js:177 is the console.log
Is this a scoping issue? Also, if it's logging prior to the push then I can see why it's coming up as undefined. How do I get around it?
I believe underscore's map produces a new array, in your case the new array will contain a bunch promises (ajax-requests)
You may want to assign this to a variable first, something like below:
getCalories: function () {
var encode = "1%20";
var calSource = "https://api.edamam.com/api/nutrition-data?app_id=#&app_key=#";
var requests = _.map(ingArray, function(elem) {
return $.ajax(calSource, {
dataType: "json",
jsonp: "jsonp",
data: "ingr=" + encode + elem
});
});
$.when.apply($, requests).then(function(results) {
console.log(results); // can you take a screenshot of this output
var calories = _.map(results, function(result) {
return JSON.parse(result.responseText).calories;
});
calArray = calArray.concat(calories);
});
}

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;
....
}
});
}

pass value to success function

is possible pass a value to success function?
function updateData(data_type){
var current_url = "myUrl";
var opc = data_type;
var dataset = [];
$.ajax({
data : {'type': opc},
url : current_url,
type : 'get',
success: function(data){
update(data)
}
});
console.log("update: " + data_type);
}
Inside the success function I want to access my data_type variable that I pass by parameter.
It this possible?
Use it directly, like this:
function updateData(data_type){
var current_url = "myUrl";
var opc = data_type;
var dataset = [];
$.ajax({
data : {'type': opc},
url : current_url,
type : 'get',
success: function(data){
update(data, data_type);
}
});
console.log("update: " + data_type);
}
function updateData( data_type ) {
var current_url = "myUrl";
var opc = data_type;
var dataset = [];
$.ajax( {
data : {'type': opc},
url : current_url,
type : 'get',
success: function( data ){
// `data_type` is available here, use as needed.
// You can pass it to other functions inside this one as well,
// i.e. the function below could be `update( data, data_type );`.
update( data );
}
} );
console.log( "update: " + data_type );
}

Add Property dynamically to the JSON array

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

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);
},
...

Categories

Resources