How to parse JSON containing HTML as HTML - javascript

I want to parse a JSON object response.indexText which contains HTML tags (validated with JSONLint).
{
"indexText": "<div id=\"content-home\"><h1> Hello World! <\/h1> <p>Some text.<\/p><p>Some more text.<\/p></div>"
}
into <div id="indexText"></div>
But when I use (EDIT after first answer. window.onload inside and outside does not change the problem.)
window.onload = function () {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let response = JSON.parse(xhttp.responseText);
document.getElementById("indexText").innerHTML = response.indexText;
}
};
xhttp.open("GET", "./json/en.json", true);
xhttp.send();
};
and reload the page it will be empty. What is going wrong? How can I parse the JSON content such that the client will render the content as HTML?
What I am trying to do. At the moment my page consists of multiple *.html files. All pages have the same navigation bar and the same footer. Only the content does change. Now I am trying to store the content inside of my JSON file such that I can change the text when clicking navigation links.

Put your code inside window.onload and you will get your required result.
Check the below working code:
window.onload = function() {
var response = {
"indexText": "<div id=\"content-home\"><h1> Hello World! <\/h1> <p>Some text.<\/p><p>Some more text.<\/p></div>"
};
document.getElementById("indexText").innerHTML = response.indexText;
};
<div id="indexText"></div>
Working JSfiddle here : https://jsfiddle.net/y2rkhp8g/1/

Related

Using button from another file

Good day! I'm new to web development and still studying.
I'm trying to create a simple counter using javascript.
index.html
<script src="test.js"></script>
<h1>Count </h1>
<p id="count">0</p>
<button onclick ="mycounter()">Add Count</button>
test.js
var counter = 0;
function mycounter(){
counter = counter + 1;
document.getElementById('count').innerHTML = counter;}
Now this code works perfectly fine. Is it possible to transfer that button to another html file and everytime that button is clicked from the other file, the count display on my index is updated?
Any help would be much appreciated. Thank you.
If you want to transfer part of your html in to another file and use it in a separate file, that is called templating. The usual pattern is to load the contents of the "other" file via XHR and add it to the DOM.
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("buttonholder").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}

Load clicked URLs from AJAX loaded page

I have the following code which fetches content from another page using AJAX:
<div id="content">
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("content").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "/Home/", true);
xhttp.send();
}
</script>
It works! Sadly, when you click on an URL from that page, all of the already loaded code disapears. :(
So my question is:
How can I make the clicked URLs load inside my DIV (content)?
Cheers.

Is it possible to load content and variables via xmlhttprequest?

is it possible to load content AND variables from a *.php-File with xmlhttprequest?
I have a index.php:
<script>
function loadsite() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("divrequest").innerHTML = this.responseText;
}
};
xhttp.open("GET", "siterequest.php", true);
xhttp.send();
}
$(document).ready(loadsite());
</script>
<div id="divrequest"></div>
My siterequest.php:
<?php
echo "some dynamic content";
echo json_encode(array($var1,$var2,$var3));
echo "more dynamic content";
?>
Am I able to get the variables? Or did I misunderstand the function of XMLHttpRequest?
EDIT:
If I use
var myvariable = JSON.parse(JSON.stringify(xhttp.responseText));
console.log(myvariable);
I will get the code of the whole page.
XMLHttpRequest sends an HTTP-request to the server to access the desired page. PHP is executed before the response data is sent back to you, in which case it's translated to HTML. Therefore, you can't get the variables using this approach with JavaScript. That happens before you even receive the data.

Retrieve a variable from server using alert

this is my first attempt to retrieve a value using an alert box. Here what I am doing is having a file at the server and I want to retrieve that file value in an alert box.
Before that, I am able to get that value through a link. That working code is here-
<!DOCTYPE html>
<html>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "localhost:8080/TemperatureReading/", true);
xhttp.send();
</script>
<body>
test
</body>
Request data
</html>
Now, what am I trying to do is have that value in an alert box every time I hit that button.
That code is here---
First I added a return statement in the function so that a variable is returned inside it.
xhttp.send();
return variable;
Than, I added another function for alert box---
<script>
function myFunction() {
alert(variable);
});
</script>
and in the body, I added
<button onclick="myFunction()">Try</button>
But till now I am not succeeded in that.
I am not understanding what am doing wrong here.
Can anyone help me with this thing. Thank you in advance.
EDIT : I have edited the code. Also, I have to only create a HTML file. I am not generating the number. So, what I have to do is just give an HTML and with the help of retrieve value
Do this when you get the response:
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
if(window.localStorage){
window.localStorage.setItem['resp'] = JSON.stringify(xhttp.responseText);//set it here
}
}
now in the function where variable is required:
function myFunction() {
if(window.localStorage){
var resp = JSON.parse(window.localStorage.getItem['resp']); // get it here
alert(resp); // alert it here.
}
}

Send javascript function parameters onChange

Okay, I've been struggling with this for a few hours now. I'm using ajax to update a div in my site with a php code however, i'm trying to send parameters in the function from the external javascript file to update the correct link(there are multiple drop down boxes)
for example: this is my select box
<script type='text/javascript' src='ajax.js'></script>//include ajax file
<select onchange='MakeRequest(raceupdate);
this.options[this.selectedIndex].value;'> //so no use of a button is needed to auto link to anchor tag
<option>Deathmateched</option>
<?php
dmList()
?>
</select>
Then next my external ajax function MakeRequest().
function MakeRequest(value)
{
var linkInfo = "teleport.php?call=" + value;//create appropriate link depending on function parameters
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", linkInfo, true); //update page using link info variable created above
xmlHttp.send(null);
}
So as you can see I'm trying to pass a sting of text into this function, but I seem to be failing somewhere.
You probably want to setup your tag to pass "this". I don't see where your raceupdate variable is declared, unless it's global... in which case you should show us what you're doing with that variable.
<select onchange='MakeRequest(this);'>
<option>Deathmateched</option>
<?php
dmList();
?>
If you did it that way, you'd have to change this function as such:
function MakeRequest(element)
{
var linkInfo = "teleport.php?call=" + element.value;//create appropriate link depending on function parameters
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", linkInfo, true); //update page using link info variable created above
xmlHttp.send(null);
}
And what are you trying to do here?
this.options[this.selectedIndex].value;
In your comments, it looks like you're saying you want to jump to an anchor tag? If so, then you would want to do something like
var anchorTag = document.getElementID("YOUR_ANCHOR_TAG_ID");
anchorTag.focus();

Categories

Resources