I'm have trouble accessing json data within the console. If for instance I wanted to type in courses[0].name or courses.length, I get the error "courses is not defined". I'm definitely missing something here but I'm unsure how to go about it. The list is generating just fine on the DOM, but I want want to access specific parts within the array.
$(document).ready(function () {
var showData = $('#show-data');
$.getJSON('../undergraduate/ug.json', function (data) {
console.log(data);
var courses = data.courses.map(function (course) {
return course.code + ': ' + course.name;
});
if (courses.length) {
var content = '<li>' + courses.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
});
<body>
Get JSON data
<div id="show-data"></div>
</body>
The json data also seems to be appearing fine initially on load within the console log:
Any help would be very appreciated. Thanks in advance!
Related
Question, why and how do i get my json api data to display. to display my api infomation
I am new to api and am trying
json data
[{"title":"One article - API 1 - 2017-04-25 15:43:20"},{"title":"Another article - API 1 - 2017-04-25 15:43:20"},{"title":"Great article - API 1 - 2017-04-25 15:43:20"}]
I have a small js file that im using to get my api
$(document).ready(function () {
$('#get-data').click(function () {
var showData = $('#show-data');
$.getJSON('https://some api ', function (data) {
console.log(data);
var items = data.title (function (item) {
return title;
});
showData.empty();
if (items.length) {
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
showData.text('Loading the JSON file.');
});
});
I then have a html part to display the api info onlick
<body>
Get JSON data
<div id="show-data"></div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="example.js"></script>
</body>
You need to iterate over the items in data to build your HTML and then append it to the showData div.
I also changed how you are building your <li> a little bit for security purposes. If you set the HTML of the <li> equal to each item's title property coming back from data, and the title contains malicious HTML/scripts, your application has been successfully compromised with an XSS attack.
As a general rule of thumb, never set HTML unless you absolutely have to - especially if it is coming from a third-party source.
$(document).ready(function() {
$('#get-data').click(function() {
var showData = $('#show-data');
$.getJSON('https://some api ', function(data) {
showData.empty();
var items = data.map(function(elem) {
return $("<li />", {
text: elem.title
});
});
var list = $('<ul />').append(items);
showData.append(list);
});
});
});
Get JSON data
<div id="show-data"></div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="example.js"></script>
There is no method data.title() you want Array#map()
Scaled down version:
$.getJSON('https://some api ', function(data) {
// map title properties into flattened array
var items = data.map(function(item) {
return item.title;
});
if (items.length) {
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
DEMO
The data returned in $.getJSON is a collection of objects. That might have been clear to you while you consoled the response.
Now, loop through data and you can access each object and insert title into li.
See a sample code below:
data.map(function(obj) {
console.log(obj.title) // use this in your <li>
})
Here,I am getting data from db in JSON format into my .js file and I am getting in div also .But I am not getting the div in my HTML page.Please can anyone tell me how to show in my HTML page.Below is my code:
My json array:
[{"chat_question_id":"1",
"chat_question_title":"What is PHP?"},
{"chat_question_id":"17",
"chat_question_title":"what is php?",}
Below is my js code:
function ChatQuestionsInfo(bRowId)
{
var actionType = "";
var hdnFlagForSearchQue = $("#hdnFlagForSearchQue").val();
if(hdnFlagForSearchQue=="insert"){
actionType = "ChatQuestionsInfo";
} else {
actionType = "searchQuestiontitle";
}
if($.trim($("#questionname").val())==""){
$("#questionname").focus();
alert("Enter Question Name");
return false;
}
if($.trim($("#technologytags").val())==""){
$("#technologytags").focus();
return false;
}
$.post(rootUrl+"includes/ajax/ajax_chat.php", {action: actionType,bRowId:bRowId,bQuestionName: $.trim($("#questionname").val()),bTechnologyTags: $.trim($("#technologytags").val())},
function(data){
var htmlText = '';
for ( var key in data ) {
htmlText += '<div class="tab-content">';
htmlText += '<div id="newquestions"> : ' + data[key].chat_question_title + '</div>';
htmlText += '</div>';
}
$('.chat_body_form').append(htmlText);
}, "json");
return false;
}
HTML code:
<div id="newquestions"></div>
I think you need to make 2 changes, 1 is in ajax_chat.php file. and second in your javascript.
Every JSON output need to have in pure JSON output, so javascript (or jquery) can easily read it. so on output of ajax_chat.php file, you have to set a header to give proper output content type.
for example
header('Content-Type:application/json');
echo json_encode('your varialbe array');
In jquery it is better to use $.each then for loop, and also you can append the data directly in the loop.
for example
function(data){
$.each(data,function(i){
$('.chat_body_form').append('<div class="tab-content"><div id="newquestions"> : '+ $(this).chat_question_title + '</div></div>';
});
}
I think these changes will work and also will be very simple and clean code to understand or change,
Thanks...
I currently have a servlet setup to send over a list of our active servers. The method grabs the servlet data, processes it, then injects the html into the datalist tag. HTML injection process works, but when I'm splitting the array by the concat separator (which I've done before), I get no values. Below I'll explain with code examples:
HTML:
<label for="server_id_text">Server ID: </label>
<input id="server_id_text" list="server_names" name="server_id" required>
<datalist id="server_names">
<!--This gets injected with the active servers grabbed through a get request-->
</datalist>
Javascript connecting to server to get data:
Note: serverList is a global variable.
var serverList = "";
function setupAutoComplete() {
$.get(baseURL + "/SupportPortal", function (data, status) {
console.debug("Status with auto comp id: " + status);
serverList = data;
console.debug("server list auto comp at post mailing: " + serverList);
});
}
This method is called in the function that is called when the onload event is called in the body tag
Here are the two methods that inject the html:
function setupServerName() {
document.getElementById("server_names").innerHTML = getServerListHTML();
}
function getServerListHTML(){
console.debug("Autocomplete process running...");
var servArr = String(serverList).split('*');
var html = '';
var temp = '<option value="{serverName}">';
console.debug("Array:" + servArr.toString());
if (serverList == 'undefined' || servArr.length == 0){
console.debug("serverList is empty...");
return '';
}
for (var i =0; i < servArr.length; ++i){
html += temp.replace("{serverName}", servArr[i]);
}
console.debug("html: " + html);
console.debug("ServList size " + servArr.length);
return html;
}
When the page loads, setupAutoCompelte() is called first. Then, setupServerName() is called.
My issue is that after I load the page, I get the correct response from the server. For instance, I'll get server1*server2 as a response to the jQuery $.get(...) call. Then I go to split the string into an array, and I get back an empty html tag (<option value="">);
Also, the debug console info are as follows:
Autocomplete process running...
Array:
html: <option value="">
ServList size 1
Status with auto comp id: success
server list auto comp at post mailing: server1*server2
Thanks for the help!
I believe that your setupServerName() function is being called before the AJAX request in setupAutoComplete() returns, so your serverList is an empty string at that point. What you need to do is populate your <datalist> from inside your AJAX callback in setupAutoComplete().
// setup autocomplete datalist
function setupAutoComplete() {
var $datalist = $('#server_names');
$.get(baseURL + '/SupportPortal').then(function (data) {
// update datalist
if (!data || !data.length) {
// no servers, empty list
$datalist.html('');
} else {
// create options html:
// reduce array of server names
// to HTML string, and set as
// innerHTML of the dataset
$datalist.html(data.split('*').reduce(function (html, server) {
return html + '<option value="' + server + '">\n';
},''));
}
});
}
// on page load, setup autocomplete
$(function () {
setupAutoComplete();
});
As you can see from "debug console info":
the get function is asyncrhonous so you need to change your setupAutoComplete get part to:
$.get(baseURL + "/SupportPortal", function (data, status) {
console.debug("Status with auto comp id: " + status);
serverList = data;
setupServerName();
console.debug("server list auto comp at post mailing: " + serverList);
});
On page load try to call directly the setupServerName function within the success event of get function. A different approach is to divide the setupServerName function so that the part related to the serverList variable becomes part of another function.
The serverList variable is global but its content is filled after the setupServerName is executed.
I am retrieving data from Parse in my Wordpress page fine. I can append the names of my objects into a page in Wordpress, but as soon as a try to append a HTML tag like <h1> or <p>, I get an error within my Chrome console:
Uncaught SyntaxError: Unexpected token ILLEGAL
Below is the code within my wordpress page that works without errors:
<div id="list1"><h1>Beer List</h1></div>
<div id="list2"><h1>Tap List</h1></div>
<script type="text/javascript">
if (typeof jQuery != 'undefined') {
Parse.initialize("", "");
var Objs = Parse.Object.extend("Obj");
var query = new Parse.Query(Objs);
query.ascending("name");
query.find({
success: function(results) {
var obj1String = '';
var obj2String = '';
for(var i=0;i<results.length;i++)
{
var object = results[i];
obj1String= obj1String +' '+object.get('name')+'</br>';
if(object.get('isObj2') == true){
obj2String = obj2String +' '+object.get('name')+'</br>';
}
}
jQuery( "#list1" ).append( obj1String );
jQuery( "#list2" ).append( obj2String );
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
</script>
But when I add, for example a tag to one of my objStrings, I get the error. i.e.:
obj1String= obj1String +'<h1>'+object.get('name')+'</h1></br>';
Here is how the page is rendering, any why the error is happening. It seems to be adding a line break when it sees those tags:
for(var i=0;i<results.length;i++)
{
var object = results[i];
obj1String= obj1String +' //line break added here
<h1>'+object.get('name')+'</h1>
<p></br>';
if(object.get('isObj2') == true){
objString = obj2String +' '+object.get('name')+'</br>';
}
I have see other threads for this error (i.e. here). But I could not get any suggestions there to work.
Any help would be greatly appreciated, thanks!
I've had a similar problem to this before and I fixed it by making sure all the HTML tags in the JavaScript are on the same line.
As for wordpress template files you can read more about it here http://codex.wordpress.org/Page_Templates. Simply it will allow you to use a PHP file as a template to display that page.
I am using a javascript Get call to grab the json data for a collection I created in deployd. I got this code directly from the deployd backend. It gives me a json array that is put into the console, but I am far from figuring out how to parse the json not sure if thats the right term, and output it into seperate p tags for each item within in the collection.
I also have included jQuery and I am assuming based on what I have looked into online that it makes it much easier to do so. Also if there is a better library than jQuery to learn to do this with, or something that makes more sense for deployd lets say Angular, I would love to be steered in the right direction.
Here is the javascript get request provided.
dpd.things.get(function (result, err) {
if(err) return console.log(err);
console.log(result);
});
I have tried looking at a example app off the deployd site to see how they did it but havent quite figured it out here is my failed attempt below
<body>
<h1>Welcome to Deployd!</h1>
<p>You've just created a Deployd app. You can add front-end files in the <code>public</code> folder.</p>
<p>If you're new to Deployd, have a look at the Getting Started Guide or <a href="http://docs.deployd.com/docs/getting-started/your-first-api.md">Hello World Tutorial<a>.</p>
<p class="hide" id="empty">You don't have any todos! Add one now:</p>
<ul id="todos" class="unstyled"></ul>
</body>
<script>
function getTodos() {
// Get all todos
dpd.things.get(function(result, err) {
if (err) {
// Alert if there's an error
return alert(err.message || "an error occurred");
}
if (!result.length) {
$('#empty').show();
}
// todos is an array
result.forEach(function(thingy) {
renderTodo(thingy);
});
});
}
function renderTodo(thingy) {
var $el = $('<li>');
// $label = $('<label class="checkbox">')});
$el.appendTo('#todos');
$('#empty').hide();
}
</script>
NEW RECCOMENDED CODE NOT WORKING
function getTodos() {
// Get all todos
dpd.things.get(function(result, err) {
if (err) {
// Alert if there's an error
return alert(err.message || "an error occurred");
}
if (!result.length) {
$('#empty').show();
}
// todos is an array
result.forEach(function(thingy) {
renderTodo(thingy);
});
});
}
function renderTodo(thingy) {
var $el = $('<li>');
$el.text(thingy);
$el.appendTo('#todos');
$('#empty').hide();
}
Here is the site running on localtunnel so you can see the console. https://twig.localtunnel.me
Try adding 'thingy' in the code so it will display the items returned from the collection; Just make sure a collection is being returned.
If thingy is plain text:
var $el = $('<li>')
$el.text(thingy);
If thingy includes html with text:
var $el = $('<li>')
$el.html(thingy);
I ended up doing this in the end based off of this stack overflow answer
dpd.things.get(function(result, error) {
console.log(result);
$.each(result, function(i,result){
content = '<p id=" ' + result.name + ' ">'
+ result.name + '</p>' + '<p>' + result.about +
'</p>' + '<p>' + result.id + '</p>'
$(content).appendTo("#test");
});
});