Failed to parse Json into Html via JavaScript - javascript

I have the following JavaScript function that is called onload of an HTML page, but my data isn't parsing nor anything can be written in html through this function:
function displaySearchResults(){
//link base para a realização de requests para a API
var requestBaseURL = "https://api.predicthq.com/v1/events?";
var startDate = "start.gte=" + sessionStorage.getItem("startDate") + "&";
var endDate = "start.lte=" + sessionStorage.getItem("endDate") + "&";
var eventType = "category=" + sessionStorage.getItem("eventType") + "&";
var countrySearch = "country=" + sessionStorage.getItem("countrySearch");
var requestURL = requestBaseURL + startDate + endDate + eventType + countrySearch;
var searchRequest = new XMLHttpRequest();
searchRequest.withCredentials = false;
searchRequest.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
var data = JSON.parse(this.responseText);
console.log(data);
//TODO parse data into lists with associated buttons
var result = data.results
var msg = ""
for (var i=0;i < result.length;i++) {
msg += ("<li>" + result[i].title + "</li>\n");
}
msg = "<li>END</li>"
document.getElementsById("searchResults").innerHTML=msg;
}
});
}
Nor any data from the request nor de END msg is passing to the this HTML page:
(...)
<script type="text/javascript" src="js/script.js"></script>
</head>
<body onload="displaySearchResults()">
<header id="header">
</header>
<div class="container">
<div class="row">
<h5>Resultados:</h5>
<ul id="searchResults">
</ul>
</div>
</div>
</body>
Ive tried calling it at the end and after the body tag, same result. If its on load why doesn't appear anything, also console shows no errors.

Try this. It has a button which on click render the List in dom.
var data = {
results: [{
title: "title1"
}, {
title: "title2"
}, {
title: "title3"
}]
}
function LoadResult() {
var result = data.results
var msg = "<ul>"
result.forEach(s => {
msg = msg + "<li>" + s.title + "</li>"
})
msg = msg + "<li>END</li></ul>"
document.getElementById("result").innerHTML = msg;
}
<html>
<body>
<button onClick="LoadResult()">Load</button>
<div id="result">
</div>
</body>
</html>

Related

display all json data with bootstrap card in a dynamic div using jquery

i'm still learning ajax,jquery and js here.. So in this problem i want to get the json data and display each of it into div id="card-body" dynamically one by one per ID, but it seems my code doesn't work because the result only show one div that have all the data inside of it. Are there any suggestion that can be added or changed within the code here?
<div class="container">
<div class="card">
<div class="card-header">
</div>
<div class="addDiv">
<div id="card-body">
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(function () {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function (result) {
$.each(result, function (index, item) {
var userId = item.userId;
var typeId = item.id;
var titleId = item.title;
var bodyId = item.body;
var $info = $("<p/>").html("user id: " + userId + "<br>"
+ "id: " + typeId + "<br>"
+ "title: " + titleId + "<br>"
+ "body: " + bodyId);
var html = '<div id="card-body>';
for (let i = 0; i < $(result).length; i++) {
const element = $(result)[i];
}
html += '</div>';
$(".addDiv").append(html);
$("div#card-body").append($info);
});
// console.log('success', result);
// console.log(result[0].body);
// console.log($(result).length);
}
});
});
</script>
for (let i = 0; i < $(result).length; i++) {
const element = $(result)[i];
}
what is here going to do?
or you mean this? --- Updated
$(function() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function(result) {
var container = $("div#list");
$.each(result, function (index, item) {
var userId = item.userId;
var id = "card-body-" + userId;
var el = $('div#' + id)
console.log(el)
var typeId = item.id;
var titleId = item.title;
var bodyId = item.body;
var $info = $('<div>').html(
"user id: " + userId + "<br>" +
"id: " + typeId + "<br>" +
"title: " + titleId + "<br>" +
"body: " + bodyId
);
if (!el.length) {
// not found, create new one
el = $('<div id="' + id + '">')
container.append(el)
}
el.append($info)
});
}
});
});

Fix on_click function to change text

When I click on a button, a function is run. This function generates a string, and I am trying to display this string to the user in the div tag.
I tried to debug this in a few ways. For example, I check that the onclick is working. So, when I click the button, I do see "Clicked!" and then "In Function". This is expected. However, after that, it is supposed to display the string generated by the listAllEvents function. However, it does not seem to be working properly. (It logs the result as expected; it just doesn't display on the screen.)
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
function myFunction() {
document.getElementById("data").innerHTML = "Clicked!";
listAllEvents()
}
function listAllEvents() {
document.getElementById("data").innerHTML = "In Function!";
var calendarId = 'primary';
var now = new Date();
var display = ""
var events = Calendar.Events.list(calendarId, {
timeMin: now.toISOString(),
maxResults: 2500,
});
if (events.items && events.items.length > 0) {
for (var i = 0; i < events.items.length; i++) {
var event = events.items[i];
if (event.start.date) {
// All-day event.
var start = new Date(event.start.date);
var end = new Date(event.end.date);
display = display + 'Start: ' + start.toLocaleDateString() + '; End: ' + end.toLocaleDateString() + ". ";
} else {
var start = new Date(event.start.dateTime);
var end = new Date(event.end.dateTime);
display = display + 'Start: ' + start.toLocaleString() + '; End: ' + end.toLocaleString() + ". ";
}
}
} else {
display = 'No events found.';
}
Logger.log('%s ', display);
document.getElementById("data").innerHTML = "Almost There";
document.getElementById("data").innerHTML = display;
}
</script>
<div id="data"> Hello! </div>
<button onclick="myFunction()">Run Function</button>
Expected, on click: Start....End.
Actual: "In Function!"
Can't use server side code on the client
The problem is that your trying to run server side code on the client.
function listAllEvents() {
document.getElementById("data").innerHTML = "In Function!";
var calendarId = 'primary';
var now = new Date();
var display = ""
var events = Calendar.Events.list(calendarId, {//This is server side Google Script
timeMin: now.toISOString(),
maxResults: 2500,
});
if (events.items && events.items.length > 0) {
for (var i = 0; i < events.items.length; i++) {
var event = events.items[i];
if (event.start.date) {
// All-day event.
var start = new Date(event.start.date);
var end = new Date(event.end.date);
display = display + 'Start: ' + start.toLocaleDateString() + '; End: ' + end.toLocaleDateString() + ". ";
} else {
var start = new Date(event.start.dateTime);
var end = new Date(event.end.dateTime);
display = display + 'Start: ' + start.toLocaleString() + '; End: ' + end.toLocaleString() + ". ";
}
}
} else {
display = 'No events found.';
}
Logger.log('%s ', display);
document.getElementById("data").innerHTML = "Almost There";
document.getElementById("data").innerHTML = display;
}
When you want to run server side google script you can call them with google.script.run
Here's a simple example of how to use google.script.run
This is the basic frame work:
Your html file:
The button click calls the Javascript function getCalendarEvents which prepares the appropriate (probably not required in this case) data to pass to the server and then it calls listCalendarEvents which is on the server. The server function gets the events and returns them to the withSuccessHandler and that handler then puts the information into the html page.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
function getCalendarEvents() {
google.script.run
.withSuccessHandler(function(eObj){
//load html with data from eObj
})
.listCalendarEvents();
}
function listAllEvents() {
}
</script>
<div id="data"> Hello! </div>
<button onclick="getCalendarEvents();">Run Function</button>
code.js:
function listCalendarEvents() {
//get all of the events
return eObj;
}
It crashes because Calendar is undefined. Your browser's console will tell you.

Cordova InAppBrowser post form to url

i'm trying to post values inappbrowser but no success.
it does open browser twice and no data posted.
var options = {
email: 'test#email.com',
item_id: 1234,
reference: 1234,
item_descr: 'description',
item_quant: 1,
item_valor: 50 * 100
};
var form = document.createElement("form");
var url = "https://testurl.com";
form.setAttribute("method","post");
form.setAttribute("action",url);
for (var data in options) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", data);
hiddenField.setAttribute("value", options[data]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
var ref = cordova.InAppBrowser.open(url, '_blank', 'location=yes');
if(ref){
form.submit();
}
Here's another way of posting a HTML form via the InAppBrowser using a dataUrl:
var pageContent = '<html><head></head><body><form id="loginForm" action="YourPostURL" method="post">' +
'<input type="hidden" name="key1" value="' + YourValue1 + '">' +
'<input type="hidden" name="key" value="' + YourValue2 + '">' +
'</form> <script type="text/javascript">document.getElementById("loginForm").submit();</script></body></html>';
var pageContentUrl = 'data:text/html;base64,' + btoa(pageContent);
var browserRef = window.cordova.InAppBrowser.open(
pageContentUrl ,
"_blank",
"hidden=no,location=no,clearsessioncache=yes,clearcache=yes"
);
you can do it like this
var options = {
email: 'test#email.com',
item_id: 1234,
reference: 1234,
item_descr: 'description',
item_quant: 1,
item_valor: 50 * 100
};
var script = 'var form = document.createElement("form");';
script += 'var url = "https://testurl.com";';
script += 'form.method="post"';
script += 'form.setAttribute("action",url);';
for (var data in options) {
script += 'var hiddenField = document.createElement("input");';
script += 'hiddenField.setAttribute("type", "hidden");';
script += 'hiddenField.setAttribute("name","' + data +'");';
script += 'hiddenField.setAttribute("value","' + options[data] + '");';
script += 'form.appendChild(hiddenField);';
}
script += 'document.body.appendChild(form)';
var ref = cordova.InAppBrowser.open(url, '_blank', 'location=yes');
script += 'form.submit();';
and then execute script in the inappbrowser using on the loadstop event like this
ref.addEventListener('loadstop', onLoadStopFunction);
onLoadStopFunction(params){
ref.executeScript({ code: script }, executeScriptCallBack);
}
function executeScriptCallBack(params) {
if (params[0] == null) {
//error message
}
}
there are many other ways to do it.
You need to fill in the dynamic feild values on loadstop or load start event by using Execute Script.
First Bind the events , when you open the link:
{
var url= 'yourURL';
if( device.platform === "Android"){
ref =cordova.InAppBrowser.open(url, "_blank",'location=no,clearcache=yes,hardwareback=no,zoom=no');
}else{
ref =cordova.InAppBrowser.open(url, "_blank",'location=no,clearcache=yes,closebuttoncaption=Go back to App,toolbar=yes,presentationstyle=formsheet');
}
ref.addEventListener('loadstart',onBrowserLoadStart);
ref.addEventListener('loadstop',onBrowserLoadStop);
ref.addEventListener('loaderror', onBrowserError);
ref.addEventListener('exit', onBrowserClose);
}
Then on onBrowserLoadStop, check if its the right page to Post form:
function onBrowserLoadStop(event){
var cUrl= 'myformURL';
if(event.url===cUrl){
var msg;
var newHtml=YourFormHTML;
var withoutScriptHtml = $(newHtml.bold());
withoutScriptHtml.find('script').remove();
msg= " var formDiv = document.createElement('div'); formDiv.id='someFormDiv'; ";
msg+= " formDiv.innerHTML='" + withoutScriptHtml.html()+ "';" ;
msg += " document.getElementById('outerDiv').appendChild(formDiv);"; //outerDiv should be on the html page residing at cUrl
msg += " document.getElementById('yourFormName').submit();";
//console.log("the message: "+ msg);
ref.executeScript(
{
code: msg
},
function(values){
console.log(JSON.stringify(values));
}
);
}
}
From the 1 page:
window.localStorage.setItem('tempForm', JSON.stringify(form));
location.replace('page2.html');
2 page:
var passedForm = $.parseJSON(window.localStorage.getItem('tempForm'));
You can do that with all objects.

How can I open with blank page on this rss javascript nor html?

I have a website which includes this RSS JavaScript. When I click feed, it opens same page, but I don't want to do that. How can I open with blank page? I have my current HTML and JavaScript below.
HTML CODE
<tr>
<td style="background-color: #808285" class="style23" >
<script type="text/javascript">
$(document).ready(function () {
$('#ticker1').rssfeed('http://www.demircelik.com.tr/map.asp').ajaxStop(function () {
$('#ticker1 div.rssBody').vTicker({ showItems: 3 });
});
});
</script>
<div id="ticker1" >
<br />
</div>
</td>
</tr>
JAVASCRIPT CODE
(function ($) {
var current = null;
$.fn.rssfeed = function (url, options) {
// Set pluign defaults
var defaults = {
limit: 10,
header: true,
titletag: 'h4',
date: true,
content: true,
snippet: true,
showerror: true,
errormsg: '',
key: null
};
var options = $.extend(defaults, options);
// Functions
return this.each(function (i, e) {
var $e = $(e);
// Add feed class to user div
if (!$e.hasClass('rssFeed')) $e.addClass('rssFeed');
// Check for valid url
if (url == null) return false;
// Create Google Feed API address
var api = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + url;
if (options.limit != null) api += "&num=" + options.limit;
if (options.key != null) api += "&key=" + options.key;
// Send request
$.getJSON(api, function (data) {
// Check for error
if (data.responseStatus == 200) {
// Process the feeds
_callback(e, data.responseData.feed, options);
}
else {
// Handle error if required
if (options.showerror) if (options.errormsg != '') {
var msg = options.errormsg;
}
else {
var msg = data.responseDetails;
};
$(e).html('<div class="rssError"><p>' + msg + '</p></div>');
};
});
});
};
// Callback function to create HTML result
var _callback = function (e, feeds, options) {
if (!feeds) {
return false;
}
var html = '';
var row = 'odd';
// Add header if required
if (options.header) html += '<div class="rssHeader">' + '' + feeds.title + '' + '</div>';
// Add body
html += '<div class="rssBody">' + '<ul>';
// Add feeds
for (var i = 0; i < feeds.entries.length; i++) {
// Get individual feed
var entry = feeds.entries[i];
// Format published date
var entryDate = new Date(entry.publishedDate);
var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
// Add feed row
html += '<li class="rssRow ' + row + '">' + '<' + options.titletag + '>' + entry.title + '</' + options.titletag + '>'
if (options.date) html += '<div>' + pubDate + '</div>'
if (options.content) {
// Use feed snippet if available and optioned
if (options.snippet && entry.contentSnippet != '') {
var content = entry.contentSnippet;
}
else {
var content = entry.content;
}
html += '<p>' + content + '</p>'
}
html += '</li>';
// Alternate row classes
if (row == 'odd') {
row = 'even';
}
else {
row = 'odd';
}
}
html += '</ul>' + '</div>'
$(e).html(html);
};
})(jQuery);
try change this:
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'
to
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'

javascript: missing : after property id

I'm trying to pass my own array of objects: results[num_row] = {'title:\'' + title + '\', ' + 'url:\'' + url + '\''};
but this returns the error in firebug
when I try: results[num_row] = {title:'Link A', url:'/page1'}
it works.
Thanks,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="styles.css" type="text/css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<script type="text/javascript">
var test = ["a","b","ab"];
var results = new Array();
function prep(){
$("#searchbox").autocomplete(results,{
formatItem: function(item) {
return item.title;
}
}).result(function(event, item) {
location.href = item.url;
});
}
$(document).ready(function(){
$.ajax({
type: "GET",
url: "links2.xml",
dataType: "xml",
success: function(xml) {
// Count elements
var count = $(xml).find('ROW').length;
// Create Array of correct length
//window.results = new Array(count);
// Set array variable
var num_row = 0;
//data string
var datastring = "";
//start of find block
$(xml).find('ROW').each(function() {
var title = $(this).find('SC_DF_FIELD_1').text();
var url = $(this).find('SC_DF_FIELD_2').text();
var support_url = $(this).find('SC_DF_FIELD_3').text();
var description = $(this).find('SC_DF_FIELD_4').text();
var contacts = $(this).find('SC_DF_FIELD_5').text();
//clean up xml variables
url = url.substring(url.indexOf('>') + 1, url.indexOf('/a') - 1);
support_url = support_url.substring(support_url.indexOf('>') + 1, support_url.indexOf('/a') - 1); /*need to clean up contacts search later */
//alert(title + '\t' + url + '\t' + support_url + '\t' + description + '\t' + contacts);
results[num_row] = {'title:\'' + title + '\', ' + 'url:\'' + url + '\''};
//results[num_row] = title;
//results[num_row] = {text:'Link A', url:'/page1'}
num_row++
// $('<div class="items"></div>').html('' + title + '').appendTo('#page-wrap');
});
//end of find block
prep();
}
});
});
</script>
</head>
<body>
<div id="page-wrap">
<FORM autocomplete="off"><INPUT id="searchbox" type="text"/>
</FORM></DIV>
</body>
</html>
That gives you a SyntaxError, the Object initializer syntax doesn't work like that.
If you want to use the title and url variables in a new object, you can easily:
//...
results[num_row] = {'title': title , 'url': url};
//...
Essentially when you write
{'title:\'' + title + '\', ' + 'url:\'' + url + '\''}
You are trying to set the value of
results[num_row]
equal to an incomplete object
{ PropertyName }
when you need
{ PropertyName : PropertyValue }
Try
results= [];
num_row = 0;
title = "myTitle";
url = "myURL";
results[num_row] = {'title': title, 'url': url}

Categories

Resources