I am new with using JSON file for web development and I got interest with it due to it usefulness and power in terms of data storage. Right now, I want to use JSON file via path instead of adding the JSON into the same page because it make the page full of JSON data. Yesterday I have the following codes but only adding the JSON file into the same page not into separate one. How can I use JSON file path instead of adding JSON into the same page?
HTML
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="form-group">
<label for="supplier_bank_name">Bank Name</label>
<select class="form-control selectpicker" data-live-search="true" id="supplier_bank_name" name="supplier_bank_name"></select>
</div>
</div>
PREVIOUS CODE
This code will work well but JSON only in the same page.
var allbanks = {
banks:[
{
"index": 0,
"bankname": "1st Source Bank",
"location": "USA",
"website": "www.1stsource.com"
},
{
"index": 1,
"bankname": "1st Summit Bank",
"location": "North America",
"website": "www.1stsummit.com"
},
{
"index": 2,
"bankname": "A.J. Smith Federal Savings Bank",
"location": "USA",
"website": "www.ajsmithbank.com"
}
]
};
$(document).ready(function () {
var listItems = '<option selected="selected" value="0">Select Bank</option>';
for (var i = 0; i < allbanks.banks.length; i++) {
listItems += "<option data-tokens='" + allbanks.banks[i].bankname + "' value='" + allbanks.banks[i].bankname + "'>" + allbanks.banks[i].bankname + "</option>";
}
$("#supplier_bank_name").html(listItems);
});
SCRIPT TODAY
Not working and looking for solution
var allbanks = (function () {
var allbanks = null;
$.ajax({
'async': false,
'global': false,
'url': 'js/allbanks.json',
'dataType': "json",
'success': function (data) {
allbanks = data;
}
});
return allbanks;
})();
$(document).ready(function () {
var listItems = '<option selected="selected" value="0">Select Bank</option>';
for (var i = 0; i < allbanks.banks.length; i++) {
listItems += "<option data-tokens='" + allbanks.banks[i].bankname + "' value='" + allbanks.banks[i].bankname + "'>" + allbanks.banks[i].bankname + "</option>";
}
$("#supplier_bank_name").html(listItems);
});
JSON
{
"banks": [
{
"index": 0,
"bankname": "1st Source Bank",
"location": "USA",
"website": "www.1stsource.com"
},
{
"index": 1,
"bankname": "1st Summit Bank",
"location": "North America",
"website": "www.1stsummit.com"
},
{
"index": 2,
"bankname": "A.J. Smith Federal Savings Bank",
"location": "USA",
"website": "www.ajsmithbank.com"
}
]
}
Since $.ajax is an asynchronous function, the code within allbanks will execute in this order:
Assign allbanks to null
Make ajax request
Return allbanks, which is still set to null because the ajax request has not returned yet.
Receive data and assign that to allbanks (This will not return out of the function and will not be set to the allbanks variable on the first line)
To fix this, you should use the data within the success portion of the ajax request.
function createSelectItems(data) {
var listItems = '<option selected="selected" value="0">Select Bank</option>';
for (var i = 0; i < data.banks.length; i++) {
listItems += "<option data-tokens='" + data.banks[i].bankname + "' value='" + data.banks[i].bankname + "'>" + data.banks[i].bankname + "</option>";
}
$("#supplier_bank_name").html(listItems);
}
$(document).ready(function () {
$.ajax({
'async': false,
'global': false,
'url': 'js/allbanks.json',
'dataType': "json",
'success': function (data) {
createSelectItems(data);
}
});
});
EDIT
See comments below:
allbank_connect.js
// Code goes here
var allbanks = (function () {
var allbanks = null;
$.ajax({
'async': false,
'global': false,
'url': 'js/allbanks.json',
'dataType': "json",
'success': function (data) {
allbanks = data;
}
});
return allbanks;
})();
$(document).ready(function () {
var listItems = '<option selected="selected" value="0">Select Bank</option>';
for (var i = 0; i < allbanks.banks.length; i++) {
listItems += "<option data-tokens='" + allbanks.banks[i].bankname + "' value='" + allbanks.banks[i].bankname + "'>" + allbanks.banks[i].bankname + "</option>";
}
$("#supplier_bank_name").html(listItems);
});
Related
I am unable to parse a JSON object (whatever.png) for some reason, I get [object%20Object] which is strange as I never have this issue, as its clearly simple to resolve or stringify and debug if in doubt.
My jQuery code:
$(function () {});
$.ajax({
url: '/shouts/get/ajax',
method: 'GET',
dataType: 'JSON',
success: function (res) {
res.forEach((element, i) => {
data = {
message: element['message'],
date: element['date'],
descr: element['descr'],
last_login: element['last_login'],
added: element['added'],
user: element['user'],
username: element['username'],
user_id: element['user_id'],
avatar: element['avatar'],
badges: element.badges
}
var result = XBBCODE.process({
text: data.message,
removeMisalignedTags: false,
addInLineBreaks: false
});
let allstring = '<div class="shoutbox-container"><span class="shoutDate" style="width:95px">' + jQuery.timeago(data.date) + ' <span style="color:#b3b3b3">ago</span><span id="user_badge_' + i + '"></span></span><span class="shoutUser"><a class="tooltip-shoutuser" title="' + data.username + '" href="/user/?id=' + data.user_id + '"><img src="' + data.avatar + '" class="shout-avatar" /></a></span><span class="shoutText">' + result.html + '</span></div><br>';
document.getElementById('shoutbox').innerHTML += allstring;
let badges = [];
data.badges.forEach(badge => {
badges.push('<img src="/images/avatars_gear/' + badge + '">').innerHTML += badges; // <--- Object bug
});
badges.forEach(badge => {
document.getElementById('user_badge_' + i).innerHTML += badge;
});
});
$('.shoutbox-container').filter(function () {
return $(this).children().length === 3;
}).filter(':odd').addClass('shoutbox_alt');
$('.shoutbox-container').each(function () {
$(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('shoutbox_alt');
});
$('.tooltip-shoutuser').tooltipster({
animation: 'grow',
delay: 200,
theme: 'tooltipster-punk'
});
}
});
JSON output from PHP:
[
{
"badges": [],
"username": "tula966",
"message": "perk added for [url=/user/?id=39691]tula966[/url]",
"avatar": "images/avatars/0f885488eb90548b5b93899615c5b838d2300bdb_thumb.jpg",
"date": "2022-02-04 01:00:01",
"last_login": "2022-02-03 12:36:06",
"user_id": "39691"
},
{
"badges": [
{
"image": "star.png",
"descr": " Star Power"
},
{
"image": "toolbox.png",
"descr": "Worker"
}
],
"username": "Tminus4",
"message": "testing testing",
"avatar": "images/avatars/8cc11eb4cb12c3d7e00abfba341c30b32ced49be_thumb.jpg",
"date": "2022-02-04 01:00:00",
"last_login": "2022-02-03 10:52:08",
"user_id": "1"
}
]
badge is not pushing the PNG file names from the JSON response to the DIV. I cant figure this out. This same code structure works perfectly on 3 other areas using the same JSON structure and logic, in fact more complex in our Site Polls area without any issues.
I also attempted to force the object with json_encode($array, JSON_FORCE_OBJECT) on the PHP side, which breaks the JS - and I have never needed to utilize that before in any case.
However this seems to differ greatly in this case. Any help is appreciated.
I have a query that fires off when a user goes to a page, which returns the on-shift points of contact for escalations. The issue I'm experiencing is that nothing is being populated into the table I have designated for these POCs. I've added my code below, including the HTML element this should be populating into, but I get no errors thrown back in the console, and I know that there is data that should populate into this as I've run the Ajax query and looked through the XML results and I can see entries that should show. I have another call on the same page that contacts another list to retrieve on-going critical incidents and that one works without any issues, so I've convinced myself that it's the .innerHTML part that's causing the issue, as the initial .innerHTML = ""; command is clearing the Placeholder text, however nothing else is being completed.
var filManager = [];
var mancontact = document.getElementById("managercontact");
function getContacts() {
$.ajax({
url: ".../_api/web/lists/getbytitle('On Shift Contacts')/items?$filter=Status eq 'In'&$select=Title,Id,Role,Status,Number,Brand",
type: "GET",
headers: {
"accept": "application/json;odata=verbose"
},
success: function(data) {
filManager = data.d.results;
filManager = filManager.filter(function(item) {
return item.Role == "Incident Manager";
});
if (filManager === undefined || filManager == 0) {
mancontact.innerHTML = "<tr><td style='font-family:Calibri'><center>There are currently no on-shift Managers</center></td></tr>";
} else {
mancontact.innerHTML = "";
mancontact += "<tr style='font-family:Calibri;font-size:14pt;text-align:center'><td colspan='3'>Manager On-Shift</td></tr><tr style='font-family:Calibri;font-size:12pt;text-align:center'><td>Name</td><td>Contact Number</td><td>Location</td></tr>";
for (var obj in filManager) {
mancontact.innerHTML += "<tr style='font-family:Calibri;font-size:12pt;text-align:center'><td>" + filManager[obj].Title + "</td><td>" + filManager[obj].Number + "</td><td>" + filManager[obj].Brand + "</td></tr>";
}
}
}
});
}
<center>
<table id="managercontact">
<tr>
<td>Placeholder</td>
</tr>
</table>
</center>
example array output from the call:
filManager = [
{ID:"1", Title: "Person1", Status: "In", Role: "Incident Controller", Brand: "Consumer", Number: "01234 567 890"},
{ID:"2", Title: "Person2", Status: "In", Role: "Incident Manager", Brand: "Consumer", Number: "01234 567 890"},
{ID:"3", Title: "Person3", Status: "Off", Role: "Incident Manager", Brand: "Business", Number: "01234 567 890"},
{ID:"4", Title: "Person4", Status: "Off", Role: "Incident Controller", Brand: "Business", Number: "01234 567 890"},];
I managed to find a missing innerHTML in the if statement. Adding in the below code instead of the if statement above has resolved this issue for me.
mancontact.innerHTML = "<tr><td style='font-family:Calibri'><center>There are currently no on-shift Managers</center></td></tr>";
} else {
mancontact.innerHTML = "";
mancontact.innerHTML += "<tr style='font-family:Calibri;font-size:14pt;text-align:center'><td colspan='3'>Manager On-Shift</td></tr><tr style='font-family:Calibri;font-size:12pt;text-align:center'><td>Name</td><td>Contact Number</td><td>Location</td></tr>";
for(var obj in filManager){
mancontact.innerHTML += "<tr style='font-family:Calibri;font-size:12pt;text-align:center'><td>" + filManager[obj].Title + "</td><td>" + filManager[obj].Number + "</td><td>" + filManager[obj].Brand + "</td></tr>";
}```
I am sending this valid JSON as a response from my webservice call
[
[
{
"id": 123,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 1234,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 12345,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 123456,
"vendorName": "MahalakshmiCounter",
"item": "Chocltae"
}
]
]
This is my Jquery
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://192.168.2.46:8086/Poller/poll/initial',
jsonpCallback: 'jsonCallback',
dataType: 'jsonp',
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.id + '</td><td>' + item.vendorName + '</td><td>' + item.item + '</td></tr>';
});
$('#records_table').append(trHTML);
},
error: function (e) {
$("#divResult").html("WebSerivce unreachable");
}
});
});
<table id="records_table" border='1'>
<tr>
<th>Rank</th>
<th>Content</th>
<th>UID</th>
</tr>
With this the result is looking like this in browser
I am editing my question
Edited Part
Due to the cross domain restrictions , i am forming my JSON into jsonp as shown below
This is my ajax jquery request
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://192.168.2.46:8086/Poller/poll/initial',
jsonpCallback: 'jsonCallback',
dataType: 'jsonp',
jsonp: false,
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.id + '</td><td>' + item.vendorName + '</td><td>' + item.item + '</td></tr>';
});
$('#records_table').append(trHTML);
doPoll();
},
error: function (e) {
$("#divResult").html("WebSerivce unreachable");
}
});
});
Due to the jsonCallback , its not forming a valid JSON response and i am getting undefined when forming the table
IS there anyway i can from the valid JSON response ??
jsonCallback([
[
{
"id": 123,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 1234,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 12345,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 123456,
"vendorName": "MahalakshmiCounter",
"item": "Chocltae"
}
]
])
You have to have one more $.each() loop:
$.each(response, function (i, item) {
$.each(item, function(_, o){
trHTML += '<tr><td>' + o.id + '</td><td>' + o.vendorName + '</td><td>' + o.item + '</td></tr>';
});
});
You appear to be having another array in that result. Try to loop one more time, like this for instance: http://jsfiddle.net/yH942/1/
$.each(jsonResponse, function(key, array) {
$.each(array, function(k, object) {
// your code goes here
});
});
Parse your object after receiving or use $.getJSON instead of $.ajax. You are trying to use a string as an object.
success: function (response) {
response = JSON.parse(response);
}
your data is an array in an array, and you consider it only as an array
try to do the same each loop on response[0] for example
EDIT
I'm not sure you can use jquery each on a JSON object, instead you should use :
for(var i in response) {
response[i]; // do something with it
}
Here is a snippet of the JSON my PHP script is echoing out:
[
{
"title": "4th of July",
"start": "2014-07-04"
},
{
"title": "5th of May",
"start": "2014-05-05"
},
{
"title": "My Birthday",
"start": "2014-02-03"
}
]
Im trying to loop through all the events and list them out.
The problem Im having is getting into the deeper section of the data. Can someone help me?
Also what if I was to add an array deeper down? Like this:
[
{
"title": "4th of July",
"start": "2014-07-04",
"activities": [
"badmitten",
"tennis"
]
}
]
Here is what I've tried:
$.getJSON("json.json", function(data) {
var items = [];
$.each(data, function(key, val) {
//items.push("<li id='" + key + "'>" + val + "</li>");
});
$.each(data, function(obj) {
$.each(obj, function(key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
});
});
});
try:
var data = [
{
"title": "4th of July",
"start": "2014-07-04"
},
{
"title": "5th of May",
"start": "2014-05-05"
},
{
"title": "My Birthday",
"start": "2014-02-03"
}
]
data.forEach(function(d){
// do whatever to each of the item in the array
console.log(d.title);
console.log(d.start);
});
for deeper section of the data, just keep drilling down using the same way. Inside the loop above:
if(d.activities && d.activites.length > 0){
d.activities.forEach(function(a){
console.log(a);
})
}
Hope that helps
A little late, since you've already accepted an answer, but if you want it to be dynamic, you could set up a recursive function, like this:
Example
function printSection(obj) {
var items = ['<ul>'];
$.each(obj, function(key, value) {
var item = '<li'+ (isNaN(key) ? ' id="'+ key +'"' : '') +'>';
if (value instanceof Object) {
item += key +':';
item += printSection(value);
} else {
item += value;
}
item += '</li>';
items.push(item);
});
items.push('</ul>');
return items.join('');
}
This way, you can add further levels of nesting without having to change the output loop.
$.getJSON('json.json', function(data) {
var result = [];
$.each(data, function() {
result.push(printSection(this));
});
$('#result').html(result.join(''));
}
I need to fetch the values from this JSON in my java script this is coming from jsp:
[{
"selectionName": "Select",
"subSelections": [{
"id": 4,
"subSelectionName": "Select",
"description": "Deepmala"
}
]
}, {
"selectionName": "week14",
"subSelections": [{
"id": 7,
"subSelectionName": "1",
"description": ""
}
]
}, {
"selectionName": "test",
"subSelections": [{
"id": 6,
"subSelectionName": "test",
"description": ""
}
]
}, {
"selectionName": "select",
"subSelections": [{
"id": 3,
"subSelectionName": "sub-select",
"description": "Created by Prakash"
}
]
}, {
"selectionName": "testcreate",
"subSelections": [{
"id": 1,
"subSelectionName": "testcreate",
"description": ""
}
]
}, {
"selectionName": "by htmlwidget",
"subSelections": [{
"id": 5,
"subSelectionName": "by htmlwidget",
"description": "created by html widget"
}
]
}
]
Any suggestions? I am tring to fetch it like this:
function getSelection() {
var options = "";
$.getJSON('../r3/selection.jsp').done(function(json) {
//alert(json.selectionName);
// alert(json.subSelections);
// options += '<option value="' + value. selectionId + '">' + value.selectionName + '</option>';
$.each(json.subSelections, function(index, value) {
options += '<option value="' + value. subSelectionName + '">' + value. description + '</option>';
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$(document.body).append(select);
}).fail(function (jqxhr, textStatus, error) {
alert(' fail json : '+error);
});
}
//alert(json.selectionName);
// alert(json.subSelections); inside the loop gives me undefined value.
Try this:
$.each(json, function (key, data) {
$.each(data.subSelections, function (index, values) {
options += '<option value="' + values.subSelectionName + '">' + values.description + '</option>';
});
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$('body').append(select);