Show enter contents of JSON - javascript

QUESTION ::
I know this is a redundant question, but I am finding little help in other similar questions...
I have a json file.
I can load the json fine, but when I try to output a specific element with this
div.innerHTML = jsonfromfile[element];
I only get this...
[object Object]
as my output...
How do I get the entire element to display instead of this [object Object]?
more code to get a feel for how it is being done up...
var activity;
function jsfr() {
$.getJSON('myjson.json', function(response){
jsonfromfile = response;
})
}
.
.
.
SOLUTION :: from Francis Stalin's answer
I added a new function...
var items;
function outty(data) {
$.each(data, function(key, val) {
items=items+key+","+val+";";
});
}
and i set the depth on the json leaving me with an object which i send to outty...
dpth = jsonfromfile["elementOne"]["elSubone"]["elsuboneSub"];
outty(dpth);
div.innerHTML=items;
here's the HTML that shows the div it all prints to...
<div class="col-rght">
<div class="text" id="postcomp"></div>
</div> <!--div class="col-rght"-->
this turns the object of your desired json depth into an ugly string that you can then format for display..
if you like html lists check out how Stalin did it, but be weary of his appendTo('div')... this will place your list in every div. Try putting the name of the class of the div you want to print to with a period leading it, appendTo('.outputbox')

you can't append the json object directly into ur html. u have to parse and convert into string
$.getJSON('myjson.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('div');
});
http://api.jquery.com/jQuery.getJSON/

Use JSON.stringify(yourjsonobjecthere)

Try div.innerHTML = JSON.stringify(jsonfromfile[element]);

Related

Can't get JSON to render correctly in dropdown

I'm trying to take JSON from a PHP file and use it to populate a dropdown box.
I'm getting the JSON just fine from the PHP file. It looks like this:
[{"state":"AL"},{"state":"AK"},{"state":"AZ"},{"state":"AR"}]
I can see in the response in developer tools that it's coming over fine. However, when I look at the JSON, line 1 is empty and everything is on line 2. Not sure if that's a problem or not.
On the HTML side, here's what I've got:
<select id="myselect"></select>
and
$.getJSON('state_get.php', function(data) {
$.each(data, function(key, val) {
$('#myselect').append("<option>"+key.text+"</option>");
})
});
What I get in my dropdowns are a bunch of options with "undefined". There appear to be one for each JSON value, so something's party right, but not all the way.
Any help would be appreciated.
The first argument to each callback is the index, second is the value also the key to the property is State not text
$.getJSON('state_get.php', function (data) {
$.each(data, function (key, val) {
$('#myselect').append("<option>" + val.state + "</option>");
})
});
First argument of $.each when looping an array is index, the second is the element of the array
Try
$('#myselect').append("<option>"+val.state+"</option>");
Each of the objects in your array would be an element
reference jQuery.each() API Docs
You object has property state, not text
$.each(data, function(key, val) {
$('#myselect').append("<option>" + val.state + "</option>");
});
Try this
$('#myselect').append("<option>"+val.state+"</option>");
Lets have dropdown like below
<select id="myselect" name="stateList" class="state-list ></select>
You can append your value like this
var stateSelector = $('select.state-list');
var option = $("<option value=''></option>");
$.each(data, function(key, val) {
option = $("<option value='" + val.state + "'>" + val.state + "</option>");
stateSelector.append(option);
});
$('.state-list').selectpicker('refresh'); // you can refresh your dropdown if required

jQuery .each() prints only last value from json

I have an issue with jQuery.each(). I retrieve json data from another php file then I want to print specific key from it.
here is the js :
<div class="row" id="fetchmember">
<script type="text/javascript">
jQuery('#group').change(function() {
var id_group = this.value;
var memberjson = "fetchmember.php?group="+id_group;
jQuery.getJSON(memberjson,function(data){
jQuery.each(data, function(i, item) {
jQuery("#fetchmember").empty().append("<li>"+item.name+"</li>");
});
});
});
</script>
</div>
JSON result from one of the selected option :
[{"id":"1645819602","name":"Michael Great","first_name":"Michael","last_name":"Great"},
{"id":"100000251643877","name":"George Pambudi","first_name":"George","last_name":"Pambudi"}]
I want to print all of name from the json, but it print only last name key of the json. I have tried to use .html() and it also returns only last name key. What's wrong with my code?
Any advice and helps would be greatly appreciated. Thank you very much
You are emptying the div first and then appending :
jQuery("#fetchmember").empty().append("<li>"+item.name+"</li>");
Instead just use :
jQuery("#fetchmember").append("<li>"+item.name+"</li>");
Don't empty it in the loop if you don't want to keep only the last data. Change your callback to
jQuery("#fetchmember").empty();
jQuery.each(data, function(i, item) {
jQuery("#fetchmember").append("<li>"+item.name+"</li>");
});
Note that you can make one append if you want :
jQuery("#fetchmember").html(data.map(function(item){
return '<li>'+item.name+'</li>'
}).join(''));

Parse JSON field names and values

I've looked half a day for a solution to this, but nothing seems to work. I want to use jQuery to load JSON from a file that essentially looks like this:
[{"field_a":"1","field_b":"1000","field_c":"PRINCIPAL CASH"},
{"field_a":"2","field_b":"2000","field_c":"TRUST ASSETS"},
{"field_a":"3","field_b":"3000","field_c":" BONDS"},
{"field_a":"4","field_b":"4000","field_c":" STOCKS"}]
What I want to do is parse the JSON to dynamically populate input fields, so something like (please note that ??field?? and ??field value?? is what I need to know):
<input id="field_a" name="field_a" value="">
<input id="field_b" name="field_b" value="">
<input id="field_c" name="field_c" value="">
<script type="text/javascript">
$(function(){
//GET THE JSON DATA
$.getJSON('../coreScripts/selectGeneralLedger.php', function(data) {
//PARSE TO FIELDS
$.each(data, function(index) {
$("#"+data[index].??field name??).attr("value", data[index].??field value??);
}) //END PARSE
}); //End get JSON
});
</script>
I know how to access the field values manually using data[index].field_a, but can't for the life of me figure out how to parse this dynamically. Any help would be appreciated.
UPDATE*
adeneo gave me the solution below in the comments. Simple. Here's the script:
var data = [{"field_a":"1","field_b":"1000","field_c":"PRINCIPAL CASH"}, {"field_a":"2","field_b":"2000","field_c":"TRUST ASSETS"}, {"field_a":"3","field_b":"3000","field_c":" BONDS"}, {"field_a":"4","field_b":"4000","field_c":" STOCKS"}];
$.each(data, function(index, obj) {
$.each(obj, function(key, value) {
$('<input />', {id: key, name:key, value:value}).appendTo('body');
});
});
If i'm not understand you, it can be an answer.
$.each(data, function(index) {
$.each(data[index] ,function(key,value){
console.log("key :" + key + " value :" + value );
})
}) //END PARSE
key variable is the answer what you request for.

$.each pass value to function

I don't know how to search this problem in Stackoverflow it gives different solutions and does not relate to my problem. So I'll be needing your help again guys.
Values of variable obj:
item.title = Title1 and Title2
item.description = Description1 and Description2
HTML FILE:
function test_pop() {
var fb_id = "xxxxxxxxxxxx";
var v_id = "xxxxxxxx";
$.post('http://mysite.com/myfile.php', {fb_id: fb_id, v_id: v_id}, function(data) {
var obj = $.parseJSON(data);
$.each(obj,function(index, item){
achievement = "You Obtained " + item.title + " " + item.description;
achievement_pop(achievement);
});
});
}
achievement_pop function:
function achievement_pop(data) {
$("#achievement_popup").html(data).show(); //DIV that should show up
}
So the problem is, when the div shows up, it only outputs:
<div> <!-- Imagine that this content is inside a DIV -->
**You Obtained Title2 Description2**
</div>
But my desire output is:
<div> <!-- Imagine that this content is inside a DIV -->
**You Obtained Title1 Description1**
**You Obtained Title2 Description2**
</div>
Hope you guys help me, thanks.
the html function is replacing the whole content of the div, it's not just adding.
A solution would be to replace
$("#achievement_popup").html(data).show();
with
$("#achievement_popup").html($("#achievement_popup").html()+data).show();
But it's a little heavy. Personally I would first build the html and use the html function only once.
Use append() to add to end of element and not replace the content completely with html()
Or if you want to replace the existing content with all the new content at once:
/* start with empty string*/
var achievement='';
$.each(obj,function(index, item){
/* add to string on each pass of loop - can use any html you want here*/
achievement += "You Obtained " + item.title + " " + item.description +'<br>';
});
/* update element once all data parsed*/
achievement_pop(achievement);
Parsing to string and making one update is the most efficient from processing standpoint

jquery: "Exception thrown and not caught" in IE8, but works in other browsers

My code works fine in other browsers, but in IE8 I get "error on page" - and when I click that it says:
"Exception thrown and not caught Line: 16 Char: 15120 Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"
I tried linking to jquery.js (rather than jquery.min.js) and to 1.5.1/jquery.min.js,
but problem still remains.
Can someone correct/improve my code for me, or guide me as to where to look. Thanks
<script type="text/javascript">
function fbFetch()
{
var token = "<<tag_removed>>&expires_in=0";
//Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
var url = "https://graph.facebook.com/<<ID_REMOVED>>?&callback=?&access_token=" + token;
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url, function(json)
{
json.data = json.data.reverse(); // need to reverse it as FB outputs it as earliest last!
var html = "<div class='facebook'>";
//loop through and within data array's retrieve the message variable.
$.each(json.data, function(i, fb)
{
html += "<div class='n' >" + fb.name;
html += "<div class='t'>" + (dateFormat(fb.start_time, "ddd, mmm dS, yyyy")) + " at " + (dateFormat(fb.start_time, "h:MMtt")) + "</div >";
html += "<div class='l'>" + fb.location + "</div >";
html += '<div class="i"><a target="_blank" title="opens in NEW window" href="https://www.facebook.com/pages/<<id_removed>>#!/event.php?eid=' + fb.id + '" >more info...</a></div>';
html += "</div >";
}
);
html += "</div>";
//A little animation once fetched
$('.facebookfeed').animate({opacity: 0}, 500, function(){
$('.facebookfeed').html(html);
});
$('.facebookfeed').animate({opacity: 1}, 500);
});
};
Does the code do the job in IE8 or does it break? The reason I ask is because if it works as expected you could just wrap it in a try{ } catch{ \\do nothing } block and put it down to another thing IE is rubbish at.
You may be better off creating an object for the creation of the facebook div. Something like...
var html = $('<div />');
html.attr('class', 'facebook');
Then in your each loop you can do this...
$('<div />').attr('class', 'n').append(fb.name).appendTo(html);
$('<div />').attr('class', 't').append etc...
Then append html to the facebookfeed object
Doing this may remove the scope for error when using single quotes and double quotes when joining strings together, which in turn may solve your issue in IE8
$('.facebookfeed').fadeOut(500, function(){
$(this).append(html).fadeIn(500);
});
Hope this helps!
UPDATE
The append method is used to add stuff to a jquery object. For more info see here
So to surround the div's as you mentioned in the comments you would do something like this...
var nDiv = $('<div />').attr('class', 'n').append(fb.name);
$('<div />').attr('class', 't').append(fb.somethingElse).appendTo(nDiv);
// etc
And then you would need to append that to the html div like so...
html.append(nDiv);
So that would give you
<div class="facebook">
<div class="n">
value of fb.name
<div class="t">
value of fb.somethingElse
</div>
</div>
</div>
So what you have done is created a new jquery object and appended to that, then appended that to the html object which you have then appended to the facebookfeed div. Confusing huh?!

Categories

Resources