Access multiple objects/arrays in JSON in jQuery $.each - javascript

I am trying to build a simple page to view messages saved in a mysql db via JSON and jQuery.
My JSON IS
{"unread_msgs":[{"id":"6","title":"33333","user1":"19","timestamp":"1383747146","client_id":"Generic"},{"id":"5","title":"42142","user1":"19","timestamp":"1383740864","client_id":"Generic"}],"read_msgs":[{"id":"4","title":"test to addnrow","user1":"19","timestamp":"1383676647","client_id":"Generic"},{"id":"2","title":"kll","user1":"19","timestamp":"1383675548","client_id":"Generic"},{"id":"1","title":"jkjljklj","user1":"19","timestamp":"1382539982","client_id":"Generic"}],"urm_t":2,"rm_t":3}
My JS
<script type="text/javascript">
function GetClientMsgs () {
$.post("assets/server/client_msgs.php",{ client_id:local_client_id } ,function(data)
{
var MsgData = $.parseJSON(data);
console.log("Msg json data parsed");
$.each(MsgData, function(key, value)
{
console.log(value);
$('#unread_row').append('<td>'+value.unread_msgs.title+'</td><td>'+value.unread_msgs.studioname+'</td><td>'+value.unread_msgs.timestamp+'</td><td>X</td>');
$('#read_row').append('<td>'+value.read_msgs.title+'</td><td>'+value.read_msgs.studioname+'</td><td>'+value.read_msgs.timestamp+'</td><td>X</td>');
});
});
}
</script>
PHP
$msgs = array('unread_msgs' => $dn1s, 'read_msgs' => $dn2s, 'urm_t' => $unread_msgs, 'rm_t' => $read_msgs);
$json = json_encode($msgs);
I am trying to post values returned such as unread_msgs.title or .id and am not able to access any of the objects. I have searched on here and could not find something specific to my structure. Thanks alot.

I would loop over the unread and read results separately, like this:
$.each(MsgData.unread_msgs, function(key, value)
{
// code append to unread row
console.log(value.id, value.title, "etc");
});
$.each(MsgData.read_msgs, function(key, value)
{
// append to append to read row
console.log(value.id, value.title, "etc");
});
Pasting your json into a formatter such as http://jsonformatter.curiousconcept.com/ can help you to see its structure.

In this row:
$('#unread_row').append('<td>'+value.unread_msgs.title+'</td><td>'+value.unread_msgs.studioname+'</td><td>'+value.unread_msgs.timestamp+'</td><td>X</td>');
You are accessing the value variable as an object, while it is in fact an array.
To access the first unread message id within your $.each loop, you would do: value[0].id.
If you are trying to get a list of unread and read messages, try to loop over them.
$.each(MsgData.unread_msgs, function(index, message) {
$('#unread_row').append('<td>' + message.id + '</td><td>.......');
});
$.each(MsgData.read_msgs, function(index, message) {
$('#read_row').append('<td>' + message.id + '</td><td>.......');
});
Or with a nested loop:
$.each(MsgData, function(key, value) {
$.each(value, function(index, message) {
$('#' + key).append('<td>' + message.id + '</td><td>....);
});
]);

Related

how to remove the chrome.storage.local

Im not getting how remove chrome.storage.local values in javascript?
i use like this but the storage value is not removing from the store:chrome.storage.local.remove(result.MyFile.Base64File);
Please check the below code, here I'm using chrome.storage.local.set to set
var obj = { DocName: "name", Base64File: "Base64string" };
chrome.storage.local.set({ 'MyFile': obj });
and chrome.storage.local.get to retrive the values
chrome.storage.local.get('MyFile', function (result) {
var PdfBase64 = result.MyFile.Base64File;
var DocumentName = result.MyFile.DocName;
}
Note: You can not remove values, you can remove indexes with specific names what causes that they gets removed WITH there values.
Tbh I could not run the code but I'm pretty sure something like this should work. But I really recommend you to avoid chrome.storage because it's some kind of "dumb" :)
So please have a look at this code:
function clearItem(symbol) {
var remove = [];
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
if (index == "symbol") remove.push(index);
});
chrome.storage.sync.remove(remove, function(Items) {
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
console.log("removed: " + index);
});
});
});
});
};

How to assign array of object to dropdown in angularjs?

Hi I am developing web application in angularjs. I have one html form with several drop downs. I am making api calls to fill data to drop down. Instead of making separate call in one call i am getting all data required to bind all drop downs.
Below is my sample data.
{"status":"Success","msg":"Success","code":"200","data":{"Education":[{"ID":1,"Education":"btech"},{"ID":2,"Education":"Bcom"},{"ID":3,"Education":"BA"},{"ID":6,"Education":"PU"}],"MaritalStatus":[{"ID":1,"MaritalStatus":"sinle"},{"ID":2,"MaritalStatus":"married"}]}
I am trying to bind it to drop down as below.
var martialstatus = new Array();
var Education = new Array();
$http.get(baseurl + 'api' + '/Customer/' + 'PersonalInfoMasters').success(function (data) {
$.map(data.data, function (item) {
Education.push(item[0]);
});
console.log(Education);
}).error(function (status) {
});
Abobe piece of code gets me first item from the each object like first item from education,martial status etc. I would like to bind education object to education array. May i know where i am missing any line of code? Any help would be appreciated.
You don't seem to do any kind of mapping from the original result, so the following would suffice:
Education = data.data.Education;
Note:
The item[0] looks strange - are you trying to achieve something with that ?
I would use lowercase for the name of the variable.
Try something like this:
var MaritalStatus = new Array();
var Education = new Array();
$http.get(baseurl + 'api' + '/Customer/' + 'PersonalInfoMasters').success(function (data) {
$.map(data.data.Education, function (item) {
Education.push(item);
});
$.map(data.data.MaritalStatus, function (item) {
MaritalStatus.push(item);
});
}).error(function (error) {
// handle API errors
});
If you do not even need to format the output, you can simply re-assign the original value of your variable.
$http.get(baseurl + 'api' + '/Customer/' + 'PersonalInfoMasters').success(function (data) {
Education = data.data.Education;
MaritalStatus = data.data.MaritalStatus;
}).error(function (error) {
// handle API errors
});
You can do it this way:
var martialstatus = new Array();
var Education = [];
$http.get(baseurl + 'api' + '/Customer/' + 'PersonalInfoMasters').success(function(data) {
$.map(data.data.Education, function(item) {
Education.push(item);
});
}).error(function(status) {
});
You just need to push item instead of item[0] in the .map() method so it takes the whole Education object and push it in your array.
Otherwise you can just use with no need to use the $.map():
Education = data.data.Education
Shouldn't it be more like:
$.map(data.data.Education, function (item) {
Education.push(item[0]);
});
?

Keep getting [object, Object] from array for $.each

I keep getting [object, Object] from array for $.each when i try and alert it.
Below is the code I am using, I have tried several different ways but this seems to be the way that works the best.
Could someone please help me out
var min_chats = [];
$(function () {
$(".append_chat").click(function () {
var chatid = $(this).attr('alt');
var data = $(this).attr('data');
min_chats.push({
"chatid": chatid,
"data": data
});
});
$("#max_close").live("click", function () {
var chatid = $(this).attr('alt');
var data = $(this).attr('data');
$.each(min_chats, function (key, val) {
alert(key + val);
});
});
});
The callback parameters for $.each are index and value, not key and value.
In your case key will contain the index of the array and val will contain your object containing 2 properties: chatid and data.
So your code should look like:
$.each(min_chats, function(index, val) {
alert(val.chatid + val.data);
});
$.each documentation: http://api.jquery.com/jquery.each/

Trouble getting getJSON to display values from array

I am having trouble displaying the contents of a $.getJSON call. I have this code which retrieves some JSON data from a page.
var loadItems = function() {
if (hasNextPage === false) {
return false
}
pageNum = pageNum + 1;
var url = baseUrl + "json/" + pageNum + '/';
var jqxhr = $.getJSON(url, function (data) {
var a = [];
$.each(data.itemList, function (item) {
a.push("<li>" + item.title + "</li>");
});
$("<ul/>", {html: a.join(" ")}).appendTo("#anchor");
});
jqxhr.complete(function () { alert('done!'); $(window).bind('scroll', loadOnScroll); });
};
The idea is just to load a page dynamically based on scroll position, and get the JSON contents of that page (for an infinite scroll effect). The JSON structure is something like this:
{ "key1": val1, "key2": val2, "itemList": [ {"title": "title", "author": "author", "id": 100, "slug": slug, }, ... ] }
The important values are in itemList, where I have to retrieve data that will get plugged into my django template, which in turn will get some data from the view. Everything seems to work just fine, except that I can't access the data in itemList. Nothing seems to get pushed into the array. because nothing gets displayed on the page (namely, the <li> that should be created). This seems to be a simple implementation of a basic ajax move, but its not working.
EDIT:
I've done some bug tracking and have found that the code never executes the $.each loop. Not sure how to resolve this though.
you should be using error log to check what is going wrong:and always use index,obj format in $.each to be safe.
$.getJSON(url).success( function( data ) {
console.log(data);
$.each(data.itemList, function (index, item) {
a.push("<li>" + item.title + "</li>");
});
$("<ul/>", {html: a.join(" ")}).appendTo("#anchor");
}).error(function(error){
console.log(error);// see if you are getting in error log..
});
and your json data is also wrong it should be something like this:
{ "key1": "val1",
"key2": "val2",
"itemList":
[
{
"title": "title", "author": "author", "id": 100, "slug": "slug"
},.......
]
}
try with corrected data it will work.
you can check your data here:http://json.parser.online.fr/
I saw the problems in your code when you using
$.each() //It should using for dictionary.
So I have two solutions for you
1) You can use forEach method.
ex:
`if(data != null && data.itemList.length > 0)
{
data.itemList.forEach(function (item) {
a.push("<li>" + item.title + "</li>");
});
}`
==> This way will work for IE 10+, and the other browers.
2) Using the $.each method
ex:
if(data != null && data.itemList.length > 0)
{
$.each(data.itemList, function (key, item) {
a.push("<li>" + item.title + "</li>");
});
}
==> Your Json data is dictionary type, so if you use $.each you need to define two variable with
key: is the key of data.
item: is the value of data.
Note: this way will be worked for all browers version.
Hope this can helps you.
It's because your 'item' is an index, not an 'object' as you want. you have to use the second parameter:
$.each(data.itemList, function (index, item) {
a.push("<li>" + item.title + "</li>");
});
also, where is hasNextPage defined? is it defined? you might also shorten that to:
if (!hasNextPage) return;

chrome.storage.sync.remove array doesn't work

I am making a small Chrome extension. I would like to use chrome.storage but I can't get it to delete multiple items (array) from storage. Single item removal works.
function clearNotes(symbol)
{
var toRemove = "{";
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
toRemove += "'" + index + "',";
});
if (toRemove.charAt(toRemove.length - 1) == ",") {
toRemove = toRemove.slice(0,- 1);
}
toRemove = "}";
alert(toRemove);
});
chrome.storage.sync.remove(toRemove, function(Items) {
alert("removed");
chrome.storage.sync.get( function(Items) {
$.each(Items, function(index, value) {
alert(index);
});
});
});
};
Nothing seems to break but the last loop that alerts out what is in the storage still shows all the values I am trying to delete.
When you pass in a string to sync.remove, Chrome will attempt to remove the one single item whose key matches the input string. If you need to remove multiple items, use an array of key values.
Also, you should move your remove call to inside your get callback.
function clearNotes(symbol)
{
// CHANGE: array, not a string
var toRemove = [];
chrome.storage.sync.get( function(Items) {
$.each(Items, function(index, value)
{
// CHANGE: add key to array
toRemove.push(index);
});
alert(toRemove);
// CHANGE: now inside callback
chrome.storage.sync.remove(toRemove, function(Items) {
alert("removed");
chrome.storage.sync.get( function(Items) {
$.each(Items, function(index, value)
{
alert(index);
});
});
});
});
};
Slightly Slimmer and updated solution
chrome.storage.sync.get(null, (data) => {
const keys = Object.keys(data).filter((x) => x.startsWith('<start-of-key>')); // Can replace `startsWith` with regex or any other string comparison
chrome.storage.sync.remove(keys);
});

Categories

Resources