Is it possible to send information from the serverside to the client side like you would with Pug or EJS but without a view engine?
Right now I am using XHTTP requests to access data but it would be a lot easier to not have to use it so much.
function getAllBears(id){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("allBear").innerHTML = this.responseText;
}
};
xhttp.open("GET", "allBears", true);
xhttp.send();
}
You can insert a script tag in HTML and stringify the variable you have on server side, then read the serialized global variable on window.
response.body = ('
<html>
<head>
...
</head>
<body>
<p>text...</p>
<script>
window.bar = ###
</script>
</body>
</html>
'.replace(###, JSON.stringify(bar))
Be careful that some patterns/chars should be replaced in the result of JSON.stringify, a much safer method is as follows:
function toJSONSafely (obj: any) {
return JSON.stringify(obj)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
.replace(/<\/script>/g, '<\\/script>')
}
User your javascript inside the html code i.e inline javascript
as shown below
<html>
<head>
</head>
<body>
<p>use this code </p>
<script>
function getAllBears(id){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("allBear").innerHTML = this.responseText;
}
};
xhttp.open("GET", "allBears", true);
xhttp.send();
}
</script>
</body>
</html>
Related
Im currently trying to parse JSON data from this api in JS but im not sure how to. As of right now when I press any buttons to give me the data, it prints the arrays out rather than the specific data I want. Ive tried to use the JSON Parse function to retrieve the specific data but it seems its not working. Any help would be greatly appreciated! URL to the API docs: https://www.balldontlie.io/#get-all-players
//Loads Player Data
function loadPlayers() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("players").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/players", true);
var data = JSON.parse(xhttp.responseText);
console.log(data["last_name"])
xhttp.send();
}
//Loads Game Data
function loadGames() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("games").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/games", true);
xhttp.send();
}
//Loads Team Data
function loadTeams() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("teams").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/teams", true);
xhttp.send();
}
<!DOCTYPE html>
<html>
<body style="background-color:peachpuff;" >
<center>NBA STATS</center>
<center><marquee behavior="scroll" direction="right" scrollamount="12.5">Data Extracted From BDL API</marquee></center>
<center> View API Docs </center>
<script src="main.js"></script>
<div id="players">
<button type="button" onclick="loadPlayers()">View Players</button>
</div>
<div id = "teams" >
<button type="button2" onclick="loadTeams()">View Teams</button>
</div>
<div id ="games">
<button type="button3" onclick="loadGames()">View Games</button>
<div>
</body>
</html>
You should parse JSON in xhttp.onreadystatechange, that's a callback when request data success.
For the players data as example, it is an object with data and meta, and the players is in data key which is an Array, so you need to loop inside the array to print the values that you needed.
Here's the example for loadPlayers(). You can apply the same concept to loadGames and loadTeams, please let me know if you still having questions.
function loadPlayers() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// parse JSON after response
var players = JSON.parse(this.responseText);
// get 'data' key inside response
var playersData = players.data;
// loop all the players
for (var player of playersData) {
// print last_name to the #players element
document.getElementById("players").innerHTML += "<br />" + player['last_name'];
}
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/players", true);
xhttp.send();
}
In function loadPlayers()
data is an array not object
My question is: Could insert a jsp response (html) in html?
I think using XmlHttpRequest.
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.jsp", true);
xhttp.send();
My question is: But if I have javascript in my jsp that it executes after page loading, is it executed like when I call jsp directly by browser url?
Thanks in advance
For example:
This is index.html
<html>
<head>
<script type="text/javascript" src="app.js"></script>
</head>
<body onload="loadInfo();">
<div id="container"></div>
</body>
This is app.js:
function loadInfo(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("container").innerHTML =this.responseText;
}
};
xhttp.open("GET", "info.html", true);
xhttp.send();
}
This is info.html (i have jsp but i think it is the same..):
<html>
<head>
<script type="text/javascript" src="info.js"></script>
</head>
<body>
<div id="body_info">This is info..</div>
<script type="text/javascript" >
console.log("wait for info..");
info();
</script>
</body>
This is info.js:
function info(){
document.getElementById("body_info").innerHTML ="info.js is executed";
}
If i call info.html, typing url in browser(example http://localhost:8000/info.html), the script is executed and i get
"info.js is executed",instead if i call index.html, maybe the xhr request not return the same but I see "This is info".
how can i resolve and accomplish this problem using xhr?
Thanks
Roberto
When you make ajax called to some page so what ever will there under <body></body> will return as response so in your code this.responseText will be having <script></script> code in it also. You can check if you are using chrome then click on element tab you will see <script></script> also which is return as response .Now,to execute this you can do like below :
function loadInfo() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("container").innerHTML = this.responseText;
//getting the script which is return as response back
var datas = document.getElementById("container").getElementsByTagName("script");
//looping unders <script></script>
for (var i = 0; i < datas.length; i++) {
console.log("inside script executing")
eval(datas[i].innerText); //executing script
}
}
};
xhttp.open("GET", "n.html", true);
xhttp.send();
}
And your script for info.html look like below :
<script>
console.log("wait for info..");
info();
function info() {
document.getElementById("body_info").innerHTML = "info.js is executed";
}
</script>
I am following a guide from w3schools trying to understand JSON better.
This is their code
https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax
This is their sample JSON file
https://www.w3schools.com/js/json_demo.txt
<!DOCTYPE html>
<html>
<body>
<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>
<p id="demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
</script>
<p>Take a look at json_demo.txt</p>
</body>
</html>
I have another example JSON file here that I want to use
https://raw.githubusercontent.com/dwyl/english-words/master/words_dictionary.json
Using the same code, apart from changing
document.getElementById("demo").innerHTML = myObj.name;
to
document.getElementById("demo").innerHTML = myObj;
It doesn't seem to bring back anything apart from [object object] and I cannot understand why, Could someone please help, thanks
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj;
}
};
xmlhttp.open("GET", "https://raw.githubusercontent.com/dwyl/english-words/master/words_dictionary.json", true);
xmlhttp.send();
</script>
</body>
</html>
If you want to print the received JSON object to the DOM, you'll need to turn it into a string. To do this, use JSON.stringify(responseText).
I need to get the IP of the client. I am able to get it through PHP variable
"$_SERVER['REMOTE_ADDR']". I get this ip from server side php to html page through AJAX request but when I want to use this IP value in JavaScript it is showing that the value is undefined.
any solution?
PHP code:
<?php echo $_SERVER['REMOTE_ADDR'];?>
HTML CODE:
<body onload='ip(); ip2();'>
<kbd id='ip' ></kbd>
JavaScript code:
function ip() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ip").innerHTML =
this.responseText;
}
};
xhttp.open("POST", "ip.php");
xhttp.send();
}
function ip2() {
setTimeout(function () {
var ip = document.getElementById("ip").value;
alert(ip);
}, 1000);
}
First of all you should validate that you are getting the right response from your AJAX request by check that the result is certainly written to the element with id attribute "ip", and than instead of using:
var ip = document.getElementById('ip').value;
You should use Node.textContent to get the text content:
var ip = document.getElementById('ip').textContent;
Code example (without AJAX request):
function ip() {
document.getElementById('ip').innerHTML = '127.0.0.1';
}
function ip2() {
setTimeout(function () {
var ip = document.getElementById('ip').textContent;
console.log(ip);
}, 1000);
}
<body onload="ip(); ip2();">
<kbd id="ip" ></kbd>
You want your Ip Address in java script , so have to put ip address in that tag i think.
<?php $ip_address = $_SERVER['REMOTE_ADDR'];?>
<body onload='ip(); ip2();'>
<kbd id='ip' ><?php echo $ip_address; ?></kbd>
<?php echo $_SERVER['REMOTE_ADDR'];?>
<html>
<head>
</head>
<body onload='ip();'>
<div id='ip' ></div>
</body>
</html>
<script>
function ip() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ip").innerHTML =
this.responseText;
ip2(this.responseText);
}
};
xhttp.open("POST", "try.php");
xhttp.send();
}
function ip2(stringvalue) {
setTimeout(
function() {
var ip = document.getElementById("ip").value;
alert(stringvalue);
},2000);
}
</script>
run this code you might found what is the problem.
I have webpage on which i run a php file by javascript as given below
<script type="text/javascript">
var bhs = document.createElement('script');
var bhs_id = "yvw3lwc1tnvqfh4k4k4hisossew";
bhs.src = "//example.com/insert.php?site=" + bhs_id + "";
document.head.appendChild(bhs);
document.write("<span id='calc'></span>");
</script>
This JavaScript successfully insert data into insert.php file and then send to database. Besides i want to show one variable value generated in insert.php file in span id calc on a webpage where from above JavaScript is executed. How to do this? Thanks in advance.
It´s better use AJAX:
function loadDoc() {
var xhttp = new XMLHttpRequest();
var bhs_id = "yvw3lwc1tnvqfh4k4k4hisossew";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert('OK!');
}
};
xhttp.open("GET", "//example.com/insert.php?site=" + bhs_id, true);
xhttp.send();
}
Reference:
http://www.w3schools.com/xml/ajax_intro.asp