We have an Ember (3.5) application. For technical reasons we need environment variables to be set on page load, as opposed to build time. We're trying to set them in index.html the following way:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>App</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
{{content-for "head"}}
<script type="application/javascript">
// Object.assign polyfill
Object.assign||Object.defineProperty(Object,"assign",{enumerable:!1,configurable:!0,writable:!0,value:function(e,r){"use strict";if(null==e)throw new TypeError("Cannot convert first argument to object");for(var t=Object(e),n=1;n<arguments.length;n++){var o=arguments[n];if(null!=o)for(var a=Object.keys(Object(o)),c=0,b=a.length;c<b;c++){var i=a[c],l=Object.getOwnPropertyDescriptor(o,i);void 0!==l&&l.enumerable&&(t[i]=o[i])}}return t}});
window.env = {};
var request = new XMLHttpRequest();
request.open('GET', '/api/frontend_settings', true);
request.send(null);
request.addEventListener('readystatechange', () => {
if (request.status === 200) {
if (request.readyState === 4) {
Object.assign(window.env, JSON.parse(request.response).settings);
}
}
}, false);
</script>
<link integrity="" rel="stylesheet" href="{{rootURL}}assets/vendor.css">
<link integrity="" rel="stylesheet" href="{{rootURL}}assets/app-frontend.css">
{{content-for "head-footer"}}
</head>
<body>
<script integrity="" src="{{rootURL}}assets/vendor.js"></script>
<script integrity="" src="{{rootURL}}assets/app-frontend.js"></script>
</body>
</html>
We added a script which makes a request to some endpoint (/api/frontend_env_vars) in the snippet. This endpoint responds with a JSON with the key-values of environment variables which we then assign to window.env.
The problem we have is that sometimes Ember scripts load before the variables have been assigned (since we do a request that takes some time to complete), which makes the application crash.
We tried the following alteration to the script, but it didn't work (the error was different, though):
<script type="application/javascript">
// Object.assign polyfill
Object.assign||Object.defineProperty(Object,"assign",{enumerable:!1,configurable:!0,writable:!0,value:function(e,r){"use strict";if(null==e)throw new TypeError("Cannot convert first argument to object");for(var t=Object(e),n=1;n<arguments.length;n++){var o=arguments[n];if(null!=o)for(var a=Object.keys(Object(o)),c=0,b=a.length;c<b;c++){var i=a[c],l=Object.getOwnPropertyDescriptor(o,i);void 0!==l&&l.enumerable&&(t[i]=o[i])}}return t}});
window.env = {};
var request = new XMLHttpRequest();
request.open('GET', '/api/frontend_env_vars', true);
request.send(null);
function loadScript(src) {
const script = document.createElement('script');
script.src = src;
document.body.append(script);
}
request.addEventListener('readystatechange', () => {
if (request.status === 200) {
if (request.readyState === 4) {
Object.assign(window.env, JSON.parse(request.response).settings);
loadScript('assets/vendor.js');
loadScript('assets/app-frontend.js');
}
}
}, false);
</script>
We accomplish this using ember-cli-server-variables
Which allows you to define variables in index.html
<html>
<head>
<meta name='your-app-token' content='example:app:token'>
<meta name='your-app-user-location' content='Denver'>
<meta name='your-app-json-data' content='{"foo":"bar"}'>
</head>
</html>
and then access them from the application.
We build our index.html on the server with the needed variables to there is no async needed to fetch them.
Related
I had similar code run before but now i've lost it. No matter what I do, it will never run the php code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function kosarica() {
var vrednost = "Itworks!";
var httpr=new XMLHttpRequest();
httpr.open("POST","izpis3.php",true);
httpr.setRequestHeader("Content-type","aplication/x-www-form-urlencode");
httpr.onreadystatechange=function(){
if(httpr.readyState==4 && httpr.status ==200){
document.getElementById("responce").innerHTML=httpr.responseText;
}
httpr.send("vrednost"+vrednost);
}
}
</script>
</head>
<body>
<p id="responce">a</p>
<button onclick="kosarica()">Click me</button>
</body>
</html>
PHP Code:
<?php
echo $_POST['vrednost'];
?>
I know that I can make code for this example all in javascript but I want to run more php code where it access my database.
It does not fail, but it does never happen. You need to move the send() outside the handler.
The content type is wrong.
You need to use an equal sign to make it a variable for PHP.
Please do not use var keyword. Use const for a constant or let for a variable.
function kosarica() {
const vrednost = "Itworks!";
const httpr = new XMLHttpRequest();
httpr.open("POST", "izpis3.php", true);
httpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpr.onreadystatechange = function () {
if (httpr.readyState === 4 && httpr.status === 200) {
document.getElementById("responce").innerHTML = httpr.responseText;
}
}
httpr.send("vrednost=" + vrednost);
}
Working with trying to learn json and ajax and how they interoperate with html and javascript
I have a php with json data inside
I am trying to get the json data formatted into the html page but I keep getting error that "callback is not a function"
I am running the php and html files on my MAMP server to simulate a api feed
I will share my html and js files
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet" type="text/css">
<script src="run2.js"></script>
<title>Ajax Demo</title>
</head>
<body>
<h1 class="title">Todays Weather Forecast</h1>
<p class="sub">Click the button the check the local weather.</p>
<button class="demo-centered" type="button" onclick="loadPhp()">Check Weather</button><br><br>
<p id="demo"></p>
</body>
</html>
var loadPhp = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
loadPhp('demo.php', function (err, data) {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
for (var i = 0; i < data.length; i++) {
for (x in data[i]) {
console.log(data[i][x]);
}
}
}
});
PHP just in case
{"coord":{"lon":-116.8,"lat":33.03},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"base":"stations","main":{"temp":293.73,"feels_like":289.89,"temp_min":289.26,"temp_max":295.93,"pressure":1016,"humidity":52},"visibility":16093,"wind":{"speed":5.7,"deg":260},"clouds":{"all":40},"dt":1589408840,"sys":{"type":1,"id":5686,"country":"US","sunrise":1589374130,"sunset":1589423903},"timezone":-25200,"id":5391832,"name":"San Diego County","cod":200}
You have to create a javascript function called callback to do what the you want the callback to do.
I am trying to implement an ajax with simple txt file but the file won't load any suggestion
the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="app.js"></script>
<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button" onclick="loadText()">Get Text File</button>
</body>
</html>
and the javascript file:
//Create event Listener of the Get Text File
function loadText(){
// Create XHR object
var xhr = new XMLHttpRequest();
// OPEN - type, url/fileName, async
//console.log(xhr);
xhr.open('GET', 'sample.txt', true);
xhr.onload = function(){
//HTTP statuses
//200: OK
//403: Forbiden
//404: Not Found
if(this.status == 200){
console.log(this.responseText);
}
//Send Request
xhr.send();
}
}
and this is the sample.txt file
This massage form the text file just to ensure you have the ability to
access the text file. so if you do good for you otherwise just keep
trying
Note, I'm trying to achieve it using vanilla javascript without any frameworks or library
As an output I get nothing once I click the button and even in the network tab in the inspector the txt file never even load.
Note, I'm using live sever on vscode
xhr.send() should be outside xhr.onload()
xhr.onload() is the callback function to be executed when the request completes successfully.
refer the docs here https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onload
and the javascript file:
//Create event Listener of the Get Text File
function loadText(){
// Create XHR object
var xhr = new XMLHttpRequest();
// OPEN - type, url/fileName, async
//console.log(xhr);
xhr.open('GET', 'sample.txt', true);
xhr.onload = function(){
//HTTP statuses
//200: OK
//403: Forbiden
//404: Not Found
if(this.status == 200){
console.log(this.responseText);
}
//Send Request
}
xhr.send();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="app.js"></script>
<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button" onclick="loadText()">Get Text File</button>
</body>
</html>
In my express application my root file app.js rendering a.html in 'a' folder but a.html is not responding to any ajax code written in ajax.js. I've shown these files below-
app.js
var express = require('express');
var app = express();
app.set(express.static('./a'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/a/a.html');
});
app.listen(3000, '127.0.0.1');
a.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="button"></button>
<script src="ajax.js"></script>
</body>
</html>
ajax.js
document.getElementById('button').addEventListener('click', trigger);
function trigger() {
var xhr = XMLHttpRequest();
xhr.open('GET', 'blah.txt', true);
xhr.onload = function() {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
}
xhr.send();
}
Here I'm providing some screenshots of directory and result
Directory
End Result
The file that you are trying to load by ajax is blah.txt, whereas the file in a directory is blah without extension, try to rename it to blah.txt or remove .txt extension from the ajax url:
xhr.open('GET', '/blah', true);
I want to make a JS Ajax request but it doesn't work.
I wrote this code:
var i=0;
function send()
{
var request = new XMLHttpRequest();
request.open("GET", 'support.html', true);
request.send(null);
request.onreadystatechange = interpretRequest;
i++;
document.getElementById("debug").innerHTML=document.getElementById("debug").innerHTML+i;
}
function interpretRequest() {
document.getElementById("answer").innerHTML=document.getElementById("answer").innerHTML+"answer received";
document.getElementById("answer").innerHTML=document.getElementById("answer").innerHTML+request.status;
document.getElementById("answer").innerHTML=document.getElementById("answer").innerHTML+request.readyState;
switch (request.readyState) {
// if readyState == 4 and status == 200
case 4:
document.getElementById("Antwort").innerHTML=document.getElementById("Antwort").innerHTML+" answer received and state 4";
if (request.status != 200) {
alert("Error"+request.status);
} else {
var content = request.responseText;
// write content
document.getElementById("content").innerHTML = content;
}
break;
default:
break;
}
}
The function send is called by an intervall every s.I see that this works because
the nummers appears in the debug div. The function interpretRequest is called too. The string "answer received" appears but there is no print out which contains the request.status. In addition case 4 is never entered and the content div stays empty.
The HTML File is:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test</title>
<script type="text/javascript" src="code.js"></script>
</head>
<body>
<div id="debug">Debug:</div>
<br /><hr />
<div id="content">HTML:</div>
<br /><hr />
<div id="answer">answer:</div>
</body>
</html>
The support.html is in the same folder and it contains:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>It works It works It works It works It workIt works</h3>
</body>
</html>
request isn't a global, so you can't access it from the interpretRequest function.
Use this instead.