How to get Json as key and value in the Ajax $.getJSON()? - javascript

I have this ajax code for getting json from Jobs.json file.
$(document).ready(function(){
$('#btn2').click( callJobs );
});
function callJobs()
{
alert("getting results...");
$.getJSON('Jobs.json', function(JSON){
$('#result').empty();
$.each(JSON.jobs, function(i, JOB){
$('#result')
.append(JOB.Job +'<br />')
.append(JOB.Priority+'<br />')
.append(JOB.DueDate+'<br />')
.append(JOB.Iscompleted+'<hr />');
});
});
}
Jobs.json code is below.
{
"jobs":[
{
"Job":"Job1",
"Priority":"Low",
"DueDate":"11.03.2013",
"Iscompleted":"No"
},
{
"Job":"Job2",
"Priority":"High",
"DueDate":"11.03.2013",
"Iscompleted" : "No"
},
{
"Job":"Job3",
"Priority":"Medium",
"DueDate":"11.03.2013",
"Iscompleted":"No"
}
]
}
Now I want to rewrite $.each function dynamically.That is, it will write the json string as key and value instead of .append() .

This would walk over the properties of each job dynamically:
$.getJSON('Jobs.json', function(JSON){
var $container = $('#result').empty();
$.each(JSON.jobs, function(i, JOB) {
$.each(JOB, function(key, value) {
$container.append(key + ': ' + value + '<br />');
});
$container.append('<hr />');
}
});
Demo

Here's my approach. I've added comments to explain the process.
$.each(JSON.jobs, function(i, JOB) {
// an empty array for the output values
var values = [];
// iterator over each property in the current JOB object
for (var prop in JOB) {
// add an item to the array in format "key: value"
values.push(prop + ': ' + JOB[prop]);
}
// join the array values using '<br />' as separator;
// append to #result and add an '<hr />' after
$('#result').append(values.join('<br />')).append('<hr />');
});
My goals for this solution were to keep it readable (at the cost of an added array), select the #result element only once, and not have to deal with knowing whether to add that last <br /> during each loop. The other solutions append an extra <br /> after the last property and before the <hr /> whereas this and your original solution do not.

Related

Use Data in JavaScript

I build this laravel query in my controller
public function getSpiel(){
$first = DB::table('Spielplan')
-> leftjoin('Verein', 'Spielplan.Heimmannschaft', '=', 'Verein.V_ID')
-> where('Spielplan_ID', '=', $spiel);
$final = DB::table('Spielplan')
-> leftjoin('Verein', 'Spielplan.Gastmannschaft', '=', 'Verein.V_ID')
-> where('Spielplan_ID', '=', $spiel)
-> union($first)
-> get();
return Responds($final);
}
The get() output of this query is like this [{"Spielplan_ID":1,"V_ID":7,"Name":"SV Werder Bremen","Liga":1},{"Spielplan_ID":1,"V_ID":1,"Name":"FC Bayern M\u00fcnchen","Liga":1}]
And now, I want to use it in my view in the java script part
$.get('/spiel?spieleID=' + spieleID, function(data){
$('#spiel').empty();
$.each(data, function(index, valueAusData){
$('#spiel').append('<option value="' + final.Heimmannschaft + '">'+final.Name+'</option>');
});
});
But what I have don't is not correct and I don't know to use this in my option part. Can anyone say how to use the values from collection in my option java script part?
Think is. This will work
$spiel = Input::get('spieleID');
$teamOutput = Spielplan::where('Spielplan_ID', '=', $spiel)->get();
return Response($teamOutput);
$('#spiel').append('<option value="' + valueAusData.Heimmannschaft + '">'+valueAusData.Heimmannschaft+'</option>');
This is exactly the same. And this one works and the other one not.
Something wrong in here
<div class="col-xs-2">
<label for="">Teamauswahl</label>
<select class="form-control input-sm" name="spiel" id="spiel">
</select>
</div>
Firstly, the logic inside your $.each is a bit off
$.get('/spiel?spieleID=' + spieleID, function (data) {
if (data.hasOwnProperty('final')) {
$('#spiel').empty();
$.each(data.final, function (index, valueAusData) {
$('#spiel').append('<option value="' + valueAusData.Heimmannschaft + '">' + valueAusData.Name + '</option>');
});
}
});
Secondly, change the return statement in your controller method from:
return Responds($final);
to
return compact('final');
Hope this helps!
You can get Name from value object
$.get('/spiel?spieleID=' + spieleID, function(data){
$('#spiel').empty();
$.each(data, function(index, value){
$('#spiel').append('<option value="' + value.V_ID + '">'+value.Name+'</option>');
});
});
Take a look at jquery document for more example http://api.jquery.com/jquery.each/
jQuery.each( array, callback )
array Type: Array The array to iterate over.
callback Type: Function( Integer indexInArray, Object value ) The
function that will be executed on every object.
Demo
var json = [{"Spielplan_ID":1,"V_ID":7,"Name":"SV Werder Bremen","Liga":1},{"Spielplan_ID":1,"V_ID":1,"Name":"FC Bayern M\u00fcnchen","Liga":1}];
$.each(json, function(index, value){
$('#spiel').append('<option value="' + value.V_ID + '">'+value.Name+'</option>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="spiel" id="spiel"></select>

Is it possible to bind events during element concatenation in a loop?

Fiddle Example
The following is an example where several buttons are rendered via a loop. I was wondering if it is possible to bind events to each button as well during the loop before the buttons are appended to a container. My example doesn't work.
Jquery
function render(){
var input = '',
array = [{'name':'Confirm','title':'This'},{'name':'Cancel','title':'That'}]
$.each(array,function(k,obj){
var name = obj.name;
input += '<h3>'+obj.title+'</h3>';
input += '<input type="submit" name="'+name+'" value="'+name+'"/>';
$(input).find('[name="'+name+'"]').click(function(){
alert(name)
/*** do some ajax things etc ***/
})
})
return input;
}
$('#box').append(render())
Yes but I wouldn't do it the way you are:
function render(target){
var array = [{'name':'Confirm','title':'This'},{'name':'Cancel','title':'That'}]
$.each(array,function(k,obj){
var name = obj.name;
var h3 = $('<h3/>').text(obj.title);
var input = $('<input/>')
.attr('type', 'submit')
.attr('name',name)
.val(name);
input.click(function() {alert('test');});
target.append(h3);
target.append(input);
})
}
$(document).ready(function(){
render($('#box'));
});
So create jquery objects that will be rendered, then attach the event to these objects. Then once the object is built ask jquery to render them.
This way jquery can keep track of the DOM elements, in your example your stringfying everything. Jquery hasn't built the DOM element at the point where your attempting to bind to them.
Fiddle
You need to use filter() to find the element by the name as there is no parent selector to find() within:
$(input).filter('[name="' + name + '"]').click(function(){
alert(this.name)
/*** do some ajax things etc ***/
})
No, you can't bind event handlers to strings. You will need to create HTML elements first. I would recommend to bind single delegated event handler after your HTML string is appended, it's also going to be much better in terms of performance:
function render() {
var input = '',
array = [{'name': 'Confirm','title': 'This'}, {'name': 'Cancel','title': 'That'}]
$.each(array, function (k, obj) {
var name = obj.name;
input += '<h3>' + obj.title + '</h3>';
input += '<input type="submit" name="' + name + '" value="' + name + '"/>';
});
return input;
}
$('#box').append(render()).on('click', 'input[name]', function() {
alert(this.name);
/** do some ajax things etc **/
});
Demo: http://jsfiddle.net/KHeZY/200/
This can be done properly by using event-delegation, But since you concerned, I just written a solution by using .add() and .filter()
function render() {
var input = '',
array = [{
'name': 'Confirm',
'title': 'This'
}, {
'name': 'Cancel',
'title': 'That'
}],
elem = $();
$.each(array, function (k, obj) {
var name = obj.name;
input += '<h3>' + obj.title + '</h3>';
input += '<input type="submit" name="' + name + '" value="' + name + '"/>';
elem = elem.add($(input));
input = "";
});
elem.filter("[name]").click(function () {
alert(this.name);
})
return elem;
}
$('#box').append(render())
DEMO

Populate two select from JSON

This is my JSON file:
{
"AL2": {
"3810": "AL2GR1",
"3814": "AL2GR2",
"3815": "AL2GR3",
},
"AN3": {
"3818": "AN3GR1",
"3819": "AN3GR2"
},
"CME": {
"2405": "CME"
}
I need to populate two select boxes. The first one let choose between first level values (AL2,AN3,CME) and the second one between the deep level ones (AL2GR#,AN3GR#,CME).
My infile Javascript is :
var jsonData = {"AL2": {"3810": "AL2GR1","3814": "AL2GR2","3815": "AL2GR3"},"AN3": {"3818": "AN3GR1","3819": "AN3GR2"},"CME": {"2405": "CME"}};
$(window).load(function(){
$.each(jsonData,function(key, value) {
$('#ue').append('<option value=' + key + '>' + key + '</option>');
});
});
function grfromue(element,jsonData) {
var ue = $("#ue option:selected").text();
alert(ue);
$.each(jsonData[ue],function(key, value) {
$('#gr').append('<option value=' + key + '>' + value + '</option>');
});
};
And HTML :
<select id="ue" onChange="grfromue(this,jsonData);">
</select>
<select id="gr">
</select>
The second select box isn't changing, what am I doing wrong ?
Below snippet of code might be helpful to you
var json = {
"AL2": {
"3810": "AL2GR1",
"3814": "AL2GR2",
"3815": "AL2GR3",
},
"AN3": {
"3818": "AN3GR1",
"3819": "AN3GR2"
},
"CME": {
"2405": "CME"
}
};
to get each value in first level
$.each( json, function( key, value ) {
console.log( key );
});
to get second level values based on your first input
input = 'AL2';
$.each( json[input], function( key, value ) {
console.log( key + ' : ' + value );
});
Hope this helps you.
You can use a nested JQuery each method to iterate over the objects and the nested objects within them. You can extend it for as many nested objects as you like.
jQuery.each(obj, function(i, val) {
console.log("Object: " + i);
jQuery.each(val, function(j, value) {
console.log('It has ' + j + ' with value ' + value);
});
});
If you want to populate the second select box based on the value of the first, you can use array notation to fetch contents of the object. Something like this:
jQuery("#selec-id").change(function(){
$("#second-select-id").html("");
jQuery.each(obj[$(this).val()], function(key, value) {
$("#second-select-id").append("<option value='"+key+"'>"+value+"</option>");
});
});

Jquery reading input field that was created from JSON loop

I cannot figure out for the life of me why this will not work. I am trying to pull the value of a textfield that was created with a loop from a json file.
In this code, at the very bottom I just do a simple click(function() {alert()} just to see if I can pull a value and its returning undefined. But if I remove '#name' and put in 'input' it captures it, but only for the first of several input fields.
Any help is really appreciated
JSON
{
"Controls": [{
"Button":[{ "Name":"Button", "x": "1","y": "2","width": "3","height": "4","Transition":"" }],
"Image":[{"x": "5","y": "6","width": "7","height": "8"}],
"TextField":[{"x": "9","y": "10","width": "11","height": "12","Rows":""}]
}]
}
The Code(there is soome getJSON stuff above this)
//Slide In Attributes Panel Based on Selected Object
$(document).on('click', '#code li', function () {
var index = $('#code li').index(this);
var selected = $(this).text();
switch (selected) {
case selected:
$('#options').hide();
hidePanels();
$('#temp').remove();
$('#objectAttributes').show("slide", 200);
break;
//If it does work show what variable is being used
default:
alert(selected);
break;
}
//Shows Selected LI Index
$('#codeIndex').text("That was div index #" + index);
//Pull list of Attributes for selected Object
$.getJSON('controls.json', function (data) {
//Build Attributes List
var attributeList = '<div id="temp">';
//Target based on selected object
var target = selected;
attributeList += '<div>' + target + '<div>';
$.each(data.Controls[0][target][0], function (kk, vv) {
attributeList += '<div style="float:right">' + kk + ':' + '<input type="text" id='+ kk + '>' + '</input>' + '</div>';
});
attributeList += '</div></div>';
attributeList += '</div>';
$('#objectAttributes').append(attributeList);
$('#temp').append('<div id="editIndex">'+"Modifying index" + " " +index+'</div>');
$(document).on('click', '#saveAttributes', function () {
var $x = $('#name').val();
alert($x);
})
});
});
Ok, so after a little hacking around with a jsfiddle the answer turned out to be a lot simpler than I first thought. Ever since HTML 4.01 class names and IDs have been case sensitive (reference), which means that your selector $('#name') wasn't matching the JSON Name.
So a simple change, such as in this simplified jsfiddle seems to work as desired. Hopefully this helps!

call an element inside json object with jquery

i am trying to call an element inside a json object, here is a part of the code
{
" academy": {
"business": {
"E-commerce": [
now i successed to call academy as the first element, by this code
$.getJSON("professorUnversityCollegeCourseData.js", function(property) {
$.each(property, function (key, value) {
$('#uni').add('<option value="'+ key + '" id="'+ count +'">'+ key +
'</option>').appendTo('#university-selection');
arrayUni[count] = key;
count++;
});
how can i get the "business" element now ?
Have you ever tried:
$.getJSON("professorUnversityCollegeCourseData.js", function(property) {
$.each(property, function (key, value){
$('#uni').add('<option value="'+ key + '" id="'+ count +'">'+ key + '</option>').appendTo('#university-selection');
arrayUni[count] = key;
count++;
alert(this.academy.business);//Or also this['academy']['business']
});
alert(property.academy.business);//Or also property['academy']['business']
});
I think what you should do is this:
$.getJSON("professorUnversityCollegeCourseData.js", function(property){
business = property.academy.business;
//-or-
business = property["academy"]["business"];
});
(according to the data you put up there.)
I assume this is what you are after
key.academy.business
It really is that simple, or :
key['academy']

Categories

Resources