innerHTML from JSON-file - javascript

I just created a Google sheet document and converted it to JSON-file.
Sheet: https://docs.google.com/spreadsheets/d/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/edit#gid=0
JSON: https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic?alt=json
Now, on the sheet I have text on cells A1 and A2.
I would like to display these lines on HTML-document.
Would somebody know how I can do this?

I think something is wrong at your JSON file, because Line 1 is missing, but based on your json here is how you can access the text:
const jsonResult = {"version":"1.0","encoding":"UTF-8","feed":{"xmlns":"http://www.w3.org/2005/Atom","xmlns$openSearch":"http://a9.com/-/spec/opensearchrss/1.0/","xmlns$gsx":"http://schemas.google.com/spreadsheets/2006/extended","id":{"$t":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic"},"updated":{"$t":"2020-01-09T13:49:33.116Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"Taulukko1"},"link":[{"rel":"alternate","type":"application/atom+xml","href":"https://docs.google.com/spreadsheets/d/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/pubhtml"},{"rel":"http://schemas.google.com/g/2005#feed","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic"},{"rel":"http://schemas.google.com/g/2005#post","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic"},{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic?alt\u003djson"}],"author":[{"name":{"$t":"contact.tjolanki"},"email":{"$t":"contact.tjolanki#gmail.com"}}],"openSearch$totalResults":{"$t":"1"},"openSearch$startIndex":{"$t":"1"},"entry":[{"id":{"$t":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic/cokwr"},"updated":{"$t":"2020-01-09T13:49:33.116Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"Line2"},"content":{"type":"text","$t":""},"link":[{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic/cokwr"}]}]}}
const entries = jsonResult.feed.entry;
entries.forEach(function (arrayItem) {
const titleObj = arrayItem.title
const text = titleObj['$t'];
console.log("title object: " + JSON.stringify(titleObj, null, 2))
console.log("Text: " + text)
document.getElementById("result").innerHTML += text;
});
<div id="result"> Text: </div>
You can use json-pretty-print to see the json more clearly.
EDIT
I don't know if the json link is updated real time when you modify the sheet but you can do this:
Make a call to your json link with $.ajax({ type: "GET".. }) in order to retrieve the whole object that I pasted in the previews snippet (Read more about request from here jquery.get )
Make a callback function in order get the content after the request is finished (Read more about callbacks from Callback_function )
Apply the function who print the text
const jsonURL = "https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic?alt=json"
function printTextFromJson(json) {
const entries = json.feed.entry;
entries.forEach(function(arrayItem) {
const titleObj = arrayItem.title
const text = titleObj['$t'];
console.log("title object: " + JSON.stringify(titleObj, null, 2))
console.log("Text: " + text)
document.getElementById("result").innerHTML += text;
});
}
function getJsonContent(callbackFunction) {
$.ajax({
type: "GET",
url: jsonURL,
success: function(returnValue) {
console.log(returnValue);
callbackFunction(returnValue); // callbackFunction is called when returnValue is ready.
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
},
dataType: "json"
});
}
getJsonContent(function(returnValue) {
printTextFromJson(returnValue)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"> Text: </div>
Sorry if the answer is a bit too complex, but everything has a start. If you have questions feel free to ask! xD
PS: try to change the sheet and run this snippet again, if it's not updating, then the two files are not in sync.

You have to import the .json-file in your js-code as an object. Then you can access to each value like you would with an "normal" object.
object.parameter

Related

Parsing BBCode on AJAX success

I am in a spot here trying to parse BBCode upon a AJAX success : item.message object. I am using jQuery 1.11. I have tried passing the var result in place of item.message, and only shows the [object] errors. I have tried wrapping item.message with XBBCODE and same thing.
Im not sure what to do, the script is great otherwise. We must parse bbcode to HTML or a method that can be managed PHP-side, but I don't think this is possible over JSON data.
Currently this is my jQuery code:
$(document).ready(function () {
$.ajax({
url: "/ajax/shoutbox.php",
method: "GET",
dataType: 'JSON',
success: function (data) {
var html_to_append = '';
$.each(data, function (i, item) {
// Object array repeated - not working
var result = XBBCODE.process({
text: 'item.message',
removeMisalignedTags: false,
addInLineBreaks: false
});
/*
currentPost = jQuery(this);
postHTML = bbcodeToHTML(currentPost.html());
currentPost.html(postHTML);
*/
html_to_append +=
'<div class="shoutbox-container"><span class="shoutDate">' +
jQuery.timeago(item.date) +
' <span style="color:#b3b3b3">ago</span></span><span class="shoutUser"><img src="' +
item.avatar +
'" class="shout-avatar" /></span><span class="shoutText">' +
item.message +
'</span></div><br>';
});
$("#shoutbox").html(html_to_append);
$(".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');
});
}
});
});
As you see, I'm trying to make use of the following javascript:
https://github.com/patorjk/Extendible-BBCode-Parser
I've followed the instructions exactly, before moving into the JS above with no success either way. I get this:
[object][Object]
For each iteration of the message object coming back (its a custom AJAX shoutbox).
Commented, you can see another method I have tried to no success. Any help is appreciated!
Update: Working
Thank you, Quiet Nguyen for the suggestion for replacing item.message with result.html and updating text: object

Async tooltip using JSON and kendo.template

I am struggeling with the KendoUI tooltip helper. Currently I am doing the following to get some tooltip information on a grid row:
$("#grid").kendoTooltip({
filter: 'td:nth-child(10)',
content: function (e) {
var template = kendo.template($("#myToolTipTemplate").html());
var dataItem = $("#grid").data("kendoGrid").dataItem(e.target.closest("tr"));
var tooltipHtml;
$.ajax({
url: DetailsURL + "/" + dataItem.Id,
async: false
}).done(function (data) { // data.Result is a JSON object from the server with details for the row
if (data.Success) {
data.Result = data.Result.replace(/null/g, "\"N/A\"");
tooltipHtml = template($.parseJSON(data.Result));
} else {
tooltipHtml = "Ooops!<br>Something went wrong (" + data.Result + ")";
}
});
return tooltipHtml;
}
});
I would like to get rid of the synchronous ajax call and make it asynchronous. I saw some asynchronous examples where the server delivers the full html, but nothing that works with JSON data from the server, that is then "compiled" via a kendo.template() to html on the client. Any suggestions how to do this?
Set the content of the tooltip to be a placeholder value (e.g.
"Loading..")
Listen for the "Show" event of the tooltip.
When the show event is triggered, start the request for JSON from the server
In the 'done' callback, execute the template, and replace the content of the tooltip with the new html in the 'done' callback
$("#ID").data("kendoTooltip").popup.wrapper.find(".k-tooltip-content").html("........");
Telerik helped me here. And, as often, it's easier than guessed..
$("#grid").kendoTooltip({
filter: 'td:nth-child(10)',
content: function (e) {
var template = kendo.template($("#myToolTipTemplate").html());
var dataItem = $("#grid").data("kendoGrid").dataItem(e.target.closest("tr"));
var tooltipHtml;
$.ajax({
url: DetailsURL + "/" + dataItem.Id,
async: false
}).done(function (data) { // data.Result is a JSON object from the server with details for the row
if (data.Success) {
data.Result = data.Result.replace(/null/g, "\"N/A\"");
tooltipHtml = template($.parseJSON(data.Result));
} else {
tooltipHtml = "Ooops!<br>Something went wrong (" + data.Result + ")";
}
// set tooltip content here (done callback of the ajax req)
e.sender.content.html(tooltipHtml);
});
}
});

Events not triggered when posting json string using jquery [duplicate]

This question already has answers here:
jQuery posting JSON
(3 answers)
Closed 8 years ago.
I'm totally new to this, so apologies if I'm not explaining this correctly.
I want to post some data in json format to a rest service. I'm trying to get this work with JQuery in a simple .cshtml (razor) page.
My json string looks like this:
{
"ListRequest":{
"Values":[
{
"Name":"SC",
"Value":"PRO001"
},
{
"Name":"PC",
"Value":"Z0R14"
}
]
}
}
I need to pass 2 values from a form into this string and then post it but I'm not sure how do I declare this in javascript and then post it to my $.post function.
My HTML looks like this:
<form action="/" id="getListForm">
<input type="text" name="txtSC">
<input type="text" name="txtPC">
<input type="submit" value="Get List">
</form>
I thought I'd just declare a var:
var jsonText = '{"ListRequest":{ "Values":[' +
'{"Name":"SC", "Value":"' + $form.find("input[name='txtSC']").val() + '"},' +
'{"Name":"PC","Value":"' + $form.find("input[name='txtPC']").val() + '"}]}}';
Is that the correct way to handle this??
Then I've got my 'post' code to test:
var posting = $.post( url, term);
posting.done(function (data) {
var content = $(data).find("#content");
$("#result").empty().append(content);
});
But whenever I call this, it put these 2 values as part of a query string, instead of doing an actual post where this data is not visible in the url.
http://localhost/WebTest/WebDataService.svc/GetList?txtSC=brc001&txtPC=12345
Can someone tell me how to fix this??
Thanks.
UPDATE:
Here is the full code from my test page as it still not working for me. I just noticed that the submit event is not triggered. It seems to be putting the textbox and value automatically because they are part of the form, but my event is definitely not triggered as I've just commented all the code and put a alert('test'); and it didn't show up.
Any ideas?
Thanks.
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript">
// Attach a submit handler to the form
$("#getListForm").submit(function (event) {
event.preventDefault();
//var jsonText = '{"ListRequest":{ "Values":[' +
// '{"Name":"SC", "Value":"' + $form.find("input[name='txtSC']").val() + '"},' +
// '{"Name":"PC","Value":"' + $form.find("input[name='txtPC']").val() + '"}]}}';
var obj = {
ListRequest: {
Values: [
{
Name: "SC",
Value: $('input[name="txtSC"]').val()
},
{
Name: "PC",
Value: $('input[name="txtPC"]').val()
}
]
}
}
var jsonObj = JSON.stringify(obj);
var $form = $(this), term = jsonText, url = 'http://localhost/WebTest/DataService.svc';
$.post(url + '/GetList', jsonObj,
function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
// Send the data using post
//var posting = $.post( url, term);
//posting.done(function (data) {
// var content = $(data).find("#content");
// $("#result").empty().append(content);
//});
});
</script>
#{
ViewBag.Title = "Json Test";
}
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
<h2>#ViewBag.Message</h2>
</hgroup>
<form id="getListForm">
<input type="text" name="txtSC">
<input type="text" name="txtPC">
<input type="submit" value="Get List">
</form>
<div id="result"></div>
Thanks.
UPDATE:
Latest code where I've updated the term to use the jsonObj and I've put my code in the $(document).ready block as suggested:
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
// Attach a submit handler to the form
$("#getDocumentListForm").submit(function (event) {
event.preventDefault();
alert('test1');
var obj = {
ListRequest: {
Values: [
{
Name: "SC",
Value: $('input[name="txtSC"]').val()
},
{
Name: "PO",
Value: $('input[name="txtPC"]').val()
}
]
}
}
var jsonObj = JSON.stringify(obj);
var $form = $(this), term = jsonObj, url = 'http://localhost/WebTest/DataService.svc';
alert(term);
alert(url);
$.post(url + 'GetList', jsonObj,
function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
//Tried posting using term but no luck. Same problem.
//$.post(url + 'GetList',
//function (data, status) {
// alert("Data: " + data + "\nStatus: " + status);
//});
// Send the data using post
//var posting = $.post(url, term);
//posting.done(function (data) {
// //var content = $(data).find("#content");
// //$("#result").empty().append(content);
// alert(data)
//});
alert('test2');
});
});
</script>
#{
ViewBag.Title = "Test";
}
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
<h2>#ViewBag.Message</h2>
</hgroup>
<form id="getDocumentListForm">
<input type="text" name="txtSC">
<input type="text" name="txtPC">
<input type="submit" value="Get Document List">
</form>
<div id="result"></div>
Finale Update on this question
MAKE SURE:
NOT TO USE IE11 WITH JQUERY, WELL AT LEAST JQUERY 2.1.1! DON'T KNOW HOW WELL IT WORKS WITH OTHER VERSIONS OF IE.
ALWAYS TEST WITH OTHER BROWSERS
MAKE SURE TO SET YOUR JQUERY SRC TO THE CORRECT HTTP OR HTTPS DEPENDING ON WHAT YOU USE.
That's it.
I suppose what's going on there is that you are trying to pass an undefined variable named term instead of jsonText, so the javascript code is throwing an uncaught exception and gets ignored, and you get a normal action from your form element.
You should pass the correct data. And also, knowing about JSON.stringify can probably save you a lot of time and headaches ;). You could build your object like so:
var obj = {
ListRequest: {
Values: [
{
Name: "SC",
Value: $('input[name="txtSC"]').val()
},
{
Name: "PC",
Value: $('input[name="txtPC"]').val()
}
]
}
};
var jsonObj = JSON.stringify(obj);
Another pitfall I can think of in your code, is that you have bound your AJAX to a click event on your submit button, or to an onsubmit event, and you are not preventDefault()ing.
Edit
Given the code you posted, you have a couple of mistakes:
Did you wrap your code into a jQuery(document).ready() block?
You commented out jsonText but still assign it to the variable term, causing an uncaught exception.
Fix these two things and your POST request will be done correctly.
On the other hand, why on Earth are you using jQuery version 1.5?

Upon querying a database, delete an item from a list obtained via getJSON

I have a list of items obtained upon querying a database. Result of the query is treated with jsonifyand finally obtained via getJson, by doing the following:
$(function() {
$.getJSON($SCRIPT_ROOT + '/appointments/', function(data) {
var output="<ul>";
for (var i in data.appts) {
output+="<li>" + data.appts[i].labo + "</li>"
}
output+="</ul>";
$("#result").html(output)
return false;
});
});
So far so good...
Now I need to give the possibility to delete each of the above listed items, by calling (for example ) the following Flaskfunction:
#app.route('/appointments/<int:appointment_id>/delete/', methods=['DELETE'])
def appointment_delete(appointment_id):
appt = db.session.query(Appointment).get(appointment_id)
db.session.delete(appt)
db.session.commit()
return jsonify({'status': 'OK'})
Unfortunately I have no clue on how it's possible to bridge these two pieces of code. Since I've being struggling on that for a while, I would appreciate any help that will allow me to get out of the mud... Thanks a lot.!
EDIT according to #dcodesmith's comment
The getJSON response:
{
"appts":[
{
"id":1,
"day":"Mardi",
"labo":"l1",
"modified":[
"21/01/2014"
],
"groups":"5",
"plage_h":"10h00",
"sem":"5",
"start":[
"28/01/2014"
]
},
{
"id":4,
"day":"Vendredi",
"labo":"l1",
"modified":[
"22/01/2014"
],
"groups":"5",
"plage_h":"10h00",
"sem":"5",
"start":[
"31/01/2014"
]
}
]
}
Changes required
Firstly, edit your output HTML to include an anchor tag which should have a data-id attribute with the appts id assigned to it.
Create a click event on the anchor tag in your list of appts
Code
$(function() {
$.getJSON($SCRIPT_ROOT + '/appointments/', function(data) {
var output = "<ul>";
for (var i in data.appts) {
var appt = data.appts[i];
output += "<li>" + appt.labo + "delete</li>"
}
output+="</ul>";
$("#result").html(output)
return false;
});
$(document).on('click', 'a.delete', deleteAppt);
function deleteAppt(e){
e.preventDefault();
var $this = $(this),
id = $this.data('id'),
url = "/appointments/" + id + "/delete/";
$.ajax({
url: url,
type: 'POST',
data: {id: id}
})
.done(function(data, textStatus, jqXHR){
if (data.status === 'OK'){
// if successful remove deleted row
$this.parent('li').remove();
}
})
.fail(function(jqXHR, textStatus, errorThrown){
//log your error here, if any is caught. This will be very helpful for debugging
})
}
});
Note: I know nothing about Flask, but this should work Ceteris Paribus

Passing variables with jQuery

i'm relatively new to jquery and javascript and am trying to pass
a unique id (number) into a flickr search function (jquery.flickr-1.0-js) like so, (number is the variable where i'm storing the unique id)
<script type="text/javascript" src="javascripts/jquery.flickr-1.0.js"></script>
<script type="text/javascript">
jQuery(function(){
jQuery(".btnRefresh").click(function(){
var number = $(this).attr("id");
$('#gallery_flickr_'+number+'').show();
jQuery('#gallery_flickr_'+number+'').html("").flickr({
api_key: "XXXXXXXXXXXXXXXXXXXXXXX",
per_page: 15
});
});
});
</script>
When i try to pass it in to the flickr-1.0.js function like so (abbreviated)
(function($) {
$.fn.flickr = function(o){
var s = {
text: $('input#flickr_search_'+number+'').val(),
};
};
})(jQuery);
i get a error
number is not defined
[Break on this error] text: $('input#flickr_search_'+numbe...] for type=='search' free text search
please help, what do i need to do to pass the variable between the two scripts?
Thanks,
Try adjusting your scripts as below:
...
jQuery('#gallery_flickr_'+number+'').html("").flickr({
api_key: "XXXXXXXXXXXXXXXXXXXXXXX",
per_page: 15,
search_text: $('input#flickr_search_'+number+'').val()
});
...
(function($) {
$.fn.flickr = function(o){
var s = {
text: o.search_text
};
};
})(jQuery);
The idea is that you need to find the search text based on the id of the clicked item. You do that in the function where the id is available, then pass the value of the input to the flickr function with the other values in the hash argument. In the flickr function you extract the named item from the hash and use the value.
You can pass parameters in JQuery very easily; for example:
$.ajax({
type: "POST",
url: "/<%=domainMap%>/registration/recieptList.jsp",
data: "patientId=" + patientId+"golbalSearch="+golbalSearch,
success: function(response){
// we have the response
$('#loadPatientReciept').html(response);
},
error: function(e){
alert('Error: ' + e);
}
});
}
I just realized 'flicker' != 'flickr'
darn you cutesy web 2.0 names!!!
Thanks!

Categories