include the JS source in the existing *.js file - javascript

I have MqttConnect.js file and mqttws31.js lib . I have to mqttws31.js all source code include my MqttConnect.js file, How it possible?.
when I copy everything from mqttws31.js and past mqttconnect.js file .that time this error occur:
ReferenceError: Messaging is not defined
if I try this way it is working fine :
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script src="http://www.hivemq.com/demos/websocket-client/js/mqttws31.js" type="text/javascript"></script>
<script src="MqttJS/MqttConnect.js"></script>
</head>
MqttConnect.js file code :
// Using the HiveMQ public Broker, with a random client Id
var client = new Messaging.Client("broker.mqttdashboard.com",8000, "myclientid_" + parseInt(Math.random() * 100, 10));
//Connect Options
var options = {
timeout: 60,
keepAliveInterval:450,
cleanSession:false,
//Gets Called if the connection has sucessfully been established
onSuccess: function () {
alert("Connected:");
},
//Gets Called if the connection could not be established
onFailure: function (message) {
alert("Connection failed -: " + message.errorMessage);
}
};
function Connect(){
try {
client.connect(options)
}
catch(err){
alert(err.message);
}
}
mqttws31.js code:
http://www.hivemq.com/demos/websocket-client/js/mqttws31.js
UPDATE
where I want use this , there have no html page

This may be due to a quirk of how JavaScript loads. You can find a good example of how it should be done in this answer.
The quick answer is to place the loading of both JavaScript files into the body of the HTML document hosting them, with the MQTT library above your script.
Do NOT just copy the library into your own file, that's very poor form and a copyright violation if you don't credit the library's source properly.

Copy content of mqttws31.js into MqttConnect.js at the top (not at the bottom) and then load MqttConnect.js file:
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script src="MqttJS/MqttConnect.js"></script>
</head>
I tried this myself, I am not getting any error. (window is undefined)

There is a dependency between the two files, that is, there is code in MqttConnect.js which needs the code in mqttws31.js in order to work properly. So I'm assuming you pasted the contents of mqttws31.js at the end of MqttConnect.js. Pasting the contents of mqttws31.js at the beginning of MqttConnect.js should fix this. Your MqttConnect.js should look like
// Contents of mqttws31.js ...
// Contents of MqttConnect.js ...

Related

Link to external file as in css o scripts but with database

What I know
As we all know in HTML files we usually use
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
to link an external css stylesheet to a html file so this last one will be formatted as we need and also we use
<head>
<script src="somescript.js"></script>
</head>
to make our html file use an external script.
Question
Is it possible to use the same approach by linking into a Viewer.html file an external file (or even more than one) to load from a simple database saved for example as csv, txt, db, json, xml, and so on?
HTML Pseudo code Example:
<head>
<database src="somedata.db"></database>
</head>
Of course, once the data is available to the html file, a js will be used to put it where it has to go, for example into a table contained into the Viewer.html file.
Punctualizzations:
No server of any kind must be involved, just only local files approach.
No frameworks (no jquery, no Node...)
I'm looking an approach that makes use just of html (HTML 5) + javascript (ES6) and the db file (*.csv, *.txt, *.json, *.xml, *.db, ...) containing only utf8 text. The records and fields in it will follow my specifics:
text field 1|text field 2|text field...|text field N
text field 1|text field 2|text field...|text field N
text field 1|text field 2|text field...|text field N
where the pipe symbol | is my custom field separator and the newline is the record separator.
Try this solution if it feel your needs. It make use of json format:
index.html:
<html>
<head>
<script id="jsonDatas" type="application/javascript" src="./datas.json"></script>
<script src="./index.js"></script>
</head>
<body onload="javascript:checkDatas();">
<div id="datas"></div>
</body>
</html>
datas.json:
let datas = [
{"firstname":"alain","lastname":"deseine"},
{"firstname":"robert","lastname":"dupont"},
{"firstname":"john","lastname":"query"},
{"firstname":"albert","lastname":"dumoulin"},
{"firstname":"bob","lastname":"thesponge"}
];
index.js:
function checkDatas(){
console.log('%o', datas);
}
With this solution you will have access of datas in local file datas.json.
UPDATE
This is the only way to achieve what you describe with local files.
Adding let datas... to datas.json is mandatory to make browser loading datas in a javascript var that you can access later. Browsers will blocks every attempt to access src loaded content for security reasons.
You can also use XMLHttpRequest or fetch to achieve what you want, but for this you need to serve your files with an HTTP server (which can be local). HTTP Server is required because file:// protocol is not supported by CORS. And CORS will block every requests originating from another server accordingly to CORS HEADERs that are set.
To bypass CORS with chrome browser, you can start chrome with thiese flags: --disable-web-security --user-data-dir see for details: Disable same origin policy in Chrome There is aloso some chrome extensions that block CORS (not tested). But ATTENTION, these solutions need user actions and they dramatically restrict browser security.
You can load the data using prefetch/preload in the link.
<link id="user_data" rel="preload" as="fetch" crossorigin="anonymous" href="user-data.json">
But your browser will not take any action on it and you can't access the loaded data in the javascript context.
In order to use the data in the javascript context, you have to call the fetch() function with the link URL. This will not load the data twice since the data is already preloaded on the page load.
function readData(selector){
const link = document.querySelector(selector)
if(link){
return fetch(link.href)
.then( res => res.json()) // use res.text() for XML or CSV
}else{
throw 'Invalid selector on loadData(selector)'
}
};
function abc(){
//...
readData('#user_data').then(data => {
console.log(data)
})
//...
}
Alternative solution
You can define your own custom element to get the desired feature
index.html
<!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">
<script src="data-loader.js"> </script>
<!-- this script must be called before the custom element -->
<data-loader id="json" src="data.json" onload="onJSONFetch"></data-loader>
<script src="script.js"> </script>
</head>
<body>
<data-loader id="phone-xml" src="phone-number.xml" onload="onXMLFetch(event)"></data-loader>
<data-loader id="user-data" src="user.csv"></data-loader>
</body>
</html>
data-loader.js
class DataLoader extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
this.load();
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'src') {
this.load();
}
}
load() {
const attr = this.getAttribute('src');
if (attr) {
fetch(attr).then(res => res.text()).then((data) => {
const event = new CustomEvent('load', { detail: data })
this.dispatchEvent(event);
const inlineEventHandlerName = this.getAttribute('onload');
const cb = inlineEventHandlerName && window[inlineEventHandlerName];
if((typeof cb) === 'function'){
cb(event);
}
})
}
}
}
customElements.define('data-loader', DataLoader);
script.js
const documentReady = () => {
document.querySelector('#user-data').addEventListener('load', function (event) {
console.log('user-data loaded', event.detail);
})
}
function onXMLFetch(event){
console.log('onXMLFetch', event.detail);
}
function onJSONFetch(event){
console.log('onJSONFetch', event.detail);
}
document.onreadystatechange = () => {
if (document.readyState === 'interactive') {
documentReady();
}
}
Thanks to Alaindeseine's answer I got some inspirations and I did this:
into any text file (so no necessarily *.json) I put these records (notice that the following is a template literal that makes use of back ticks `, not single ' or double " quotes):
var db =
`
my data field | my data field | my data field | my data field
my data field | my data field | my data field | my data field
my data field | my data field | my data field | my data field
`
Also because of the use of var instead of let, I have the advantage that the variable db gets hoisted so I can make use of it everywhere into the file and get its content from any other script or function. Also it can be potentially declared and overwritten multiple times after the previous one is elaborated so it will be also possible to queue multiple db files to show them into the same viewer.html, which is a great advantage, for my case at least.
I already tried this way with different text file types and works great. For example I've tested
*.json
*.tsv
*.csv
*.txt
*.db
*.ext
*(no extension at all)
So at this point I believe that this can also handle other generic files extensions, at the condition they contain text enclosed into a template literal, similarly to the above.
Of course into the html file I have to point/link to the database file as if it was a script like the following:
<script src="someDBfile.ext"></script> // This links the database
<script src="myJavascript.js"></script> //This links the javascript functions that get the data from the **db** variable and create the table/s to show the well formatted data contained into the database.
Nevertheless let's hope browser developers will implement in browsers a standard and more semantically correct way of doing this with an appropriate and semantically correct tag as
<database src="somedata.db"></database>
that works similarly.
Also such procedure allows me to have just one Viewer.html to use to show all compatible files, which is also great.

Sibling text file string to blob in JavaScript - unavailable?

I have a text file (here big_buck_bunny_trailer_480p.srt), "sibling" to a html page (so when I run the html page locally, it is a local file - when I run it on server, it is a remote file) - the directory structure is:
.
├── big_buck_bunny_trailer_480p.srt
└── ttt.html
I'm trying to read the text file using XMLHttpRequest; that succeeds fine, and I can get the string content of the text file. But when I try to create a Blob out of it, in Firefox 60 console I get "unavailable".
This is my test file, ttt.html:
<script type="text/javascript">
function reqListener () {
console.log(this.responseText);
var myblob = new Blob([this.responseText], {
type: 'text/plain'
});
console.log(myblob);
}
var oReq = new XMLHttpRequest(); // "To read files that are siblings of the HTML document, use XMLHttpRequest"
oReq.addEventListener("load", reqListener);
oReq.open("GET", "big_buck_bunny_trailer_480p.srt");
oReq.send();
</script>
When I run it in Firefox 60, console prints out:
1 ttt.html:4:3
00:00:00,005 --> 00:00:03,800
The peach open movie project presents
(...)
<unavailable> ttt.html:8:3
The character encoding of the HTML document was not declared. ...
XML Parsing Error: syntax error
Location: file:///tmp/test/big_buck_bunny_trailer_480p.srt
Line Number 1, Column 1: big_buck_bunny_trailer_480p.srt:1:1
So, I get the string right - but why is the Blob <unavailable>? How can I get a Blob out of this string?
Bonus question: I get why the warning "The character encoding of the HTML document was not declared" appears, - after all, I don't even have <html> in my html file. BUt why does XML Parsing Error: syntax error appear? All I asked for was to read this file, not parse it? If the parsing is automatic, can I prevent it somehow - all I need are the string contents?
EDIT: reduced the example to this:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
var myblob = new Blob([window.btoa("Hello world")], {
type: 'text/plain'
});
console.log(myblob);
</script>
</head>
</html>
... and accessed it by using python -m SimpleHTTPServer, so via http://127.0.0.1:8000/ttt.html; and the only printout I get in the console is:
<unavailable> ttt.html:22:3
So, how do I get an actual blob from a string?
your html tags may interrupt the xml parsing. That's why its throwing Syntax Error. That kind of error is very common in JSON or XML parsing. Before create Blob, encode the Response Data.
Try this,
new Blob([window.btoa(this.responseText)], {
type: 'text/plain'
});
And also, When you retrieve the data from Blob. You need to decode using window.atob().
There are many things that browsers won't allow to happen over the file:// protocol. This is probably one of them.
Instead of running it over the file:// protocol, it is better to use a small local server to run it over. There are lots of them out there, so lots of options. Many IDEs even have them built in. I like to write a quick 10-line version with Express and Node. Whichever you chose, it'll just serve up static files for you over the http:// protocol so you can avoid these issues.
Got it, finally - turns out, if you watch console.log(myblob); in Firefox 60 Browser Console (Ctrl-Shift-J, the one in standalone window), then you get <unavailable>; but if at the same time, you observe the Web Console (Ctrl-Shift-K, sits in a tab near the Inspector of Inspect Element right-click), then you get a proper printout; see .gif:
Here it is accessed via a local server, so through http://127.0.0.1:8000/ttt.html - but accessing it locally via file:// protocol yields the exact same results (the blob can be seen in Web console to be instantiated fine, regardless of protocol).
For reference, here is the final ttt.html I used while capturing the .gif video:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function reqListener () {
console.log(this.responseText.substr(0,60)+"...");
var myblob = new Blob([window.btoa(this.responseText)], {
type: 'text/plain'
});
console.log(myblob);
}
var oReq = new XMLHttpRequest(); // "To read files that are siblings of the HTML document, use XMLHttpRequest"
oReq.overrideMimeType("text/plain");
oReq.addEventListener("load", reqListener);
oReq.open("GET", "big_buck_bunny_trailer_480p.srt");
oReq.send();
</script>
</head>
</html>

JavaScript - order of execution of <script> tags

As stated in this SO question and many other similar, the order of execution of <script>s on the page should be the same as the order in which these tags are defined in the html document.
I created a simple Java (server side) test app that allows to execute a request and wait specified period of time before returning a response (relevant code snippet at the bottom of this question). It has a simple API:
http://localhost:8080/latency?time=XXX&response=YYY
Example request that will return console.log('done') after one second (1000ms):
http://localhost:8080/latency?time=1000&response=console.log(%27done%27)
Next I created a simple index.html page (served by nginx):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test order</title>
</head>
<body>
<script type="text/javascript" async=false src="http://localhost:8080/latency?time=1000&response=console.log(%27done1%27)"></script>
<script type="text/javascript" async=false src="http://localhost:8080/latency?time=100&response=console.log(%27done2%27)"></script>
<script type="text/javascript" async=false src="http://localhost:8080/latency?time=10&response=console.log(%27done3%27)"></script>
<script>console.log('static script without "src" attr');</script>
</body>
</html>
According to everything I read so far I expected the order of console output to be:
done1
done2
done3
static script without "src" attr
This is what I got (Firefox 51 dev console):
This is just the opposite order of what I expected to get. Am I missing something? Is there a way to execute these scripts in the desired order (i.e. in the order they are defined in HTML)?
As a reference, the Java part on a server side:
private String latency(HttpServletRequest request) {
long millis = Long.parseLong(request.getParameter("time"));
String response = request.getParameter("response");
try {
Thread.sleep(millis);
return (response != null) ? response : "";
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
async is a boolean attribute. Its value does not matter. Remove the attribute.

Unexpected token < in first line of HTML

I have an HTML file :
<!DOCTYPE HTML>
<html lang="en-US" ng-app="Todo">
<head>
<meta charset="UTF-8">
<title>DemoAPI</title>
<meta name="viewport">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<link rel="stylesheet" href="./Client/css/styling.css" />
<script type="text/javascript" src="core.js"></script>
</head>
The error says:
Uncaught SyntaxError: Unexpected token < core.js: 1
It shows the error at <!doctype html> of the app.html.
core.js looks like this:
angular.module('Todo', [])
.controller('mainController', function($scope, $http)
{
$scope.formData = {};
// get all and show them
$http.get('/musicians')
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
//get with an id
$scope.getOneTodo = function() {
$http.get('/musicians' + id)
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
// send the text to the node API
$scope.createTodo = function() {
$http.post('/musicians', $scope.formData)
.success(function(data) {
$scope.formData = {}; // clear the form
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
})
};
// delete
$scope.deleteTodo = function(id) {
$http.delete('/musicians' + id)
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
/*
$scope.updateTodo = function(id) {
$http.delete('/musicians' + id)
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};*/
});
It also gives me Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.14/$injector/modulerr?p0=Todo&p1=Error%3A%2…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A17%3A381)
Besides, in console, when I click at core.js, it shows the contents of app.html and name it core.js.
Here is the snapshot:
Also, as in the image, when I click index.html, it shows app.html. However, I do not have any file that is named index.html and I load app.html by default instead of index.html.
I have tried adding/removing type="text/javascript" but no help with that either.
Also, status 200 is returned on get request for core.js.
What might be wrong?
Your page references a Javascript file at /Client/public/core.js.
This file probably can't be found, producing either the website's frontpage or an HTML error page instead. This is a pretty common issue for eg. websites running on an Apache server where paths are redirected by default to index.php.
If that's the case, make sure you replace /Client/public/core.js in your script tag <script type="text/javascript" src="/Client/public/core.js"></script> with the correct file path or put the missing file core.js at location /Client/public/ to fix your error!
If you do already find a file named core.js at /Client/public/ and the browser still produces a HTML page instead, check the permissions for folder and file. Either of these might be lacking the proper permissions.
In my case I got this error because of a line
<script src="#"></script>
Chrome tried to interpret the current HTML file then as javascript.
I experienced this error with my WordPress site but I saw that there were two indexes showing in my developer tools sources.
Chrome Developer Tool Error
So I had the thought that if there are two indexes starting at the first line of code then there's a replication and they're conflicting with each other. So I thought that then perhaps it's my HTML minification from my caching plugin tool.
So I turned off the HTML minify setting and deleted my cache. And poof! It worked!
Check your encoding, i got something similar once because of the BOM.
Make sure the core.js file is encoded in utf-8 without BOM
Well... I flipped the internet upside down three times but did not find anything that might help me because it was a Drupal project rather than other scenarios people described.
My problem was that someone in the project added a js which his address was: <script src="http://base_url/?p4sxbt"></script> and it was attached in this way:
drupal_add_js('',
array('scope' => 'footer', 'weight' => 5)
);
Hope this will help someone in the future.
We had the same problem sometime ago where a site suddenly began giving this error. The reason was that a js include was temporarily remarked with a # (i.e. src="#./js...").
I had this problem in an ASP.NET application, specifically a Web Forms.
I was forcing a redirect in Global.asax, but I forgot to check if the request was for resources like css, javascript, etc. I just had to add the following checks:
VB.NET
If Not Response.IsRequestBeingRedirected _
And Not Request.Url.AbsoluteUri.Contains(".WebResource") _
And Not Request.Url.AbsoluteUri.Contains(".css") _
And Not Request.Url.AbsoluteUri.Contains(".js") _
And Not Request.Url.AbsoluteUri.Contains("images/") _
And Not Request.Url.AbsoluteUri.Contains("favicon") Then
Response.Redirect("~/change-password.aspx")
End If
I was forcing logged users which hadn't change their passwords for a long time, to be redirected to the change-password.aspx page. I believe there is a better way to check this, but for now, this worked. Should I find a better solution, I edit my answer.
For me this was a case that the Script path wouldn't load - I had incorrectly linked it. Check your script files - even if no path error is reported - actually load.
I had the same issue. I published the angular/core application on iis.
To change the Identity of the application pool solved my issue. Now the Identity is LocalSystem
I also faced same issue.
In my case when I changed script attribute src to correct path error got fixed.
<script src="correct path"> </script>
I got my problem fix by removing slash / at the and of link tag.
<link rel="manifest" type="application/manifest+json" href="https://kal.my.id/manifest.webmanifest" title="YakaLee">
i seen your's
<link rel="stylesheet" href="./Client/css/styling.css" />
try remove the slash like so:
<link rel="stylesheet" href="./Client/css/styling.css">
I was facing the same issue recently. The js path which I provided inside my HTML file was correct. Still, during the time of calling the js file, it was prompting me an uncaught exception in the console. Furthermore, my app is running fine on localhost but facing the issue on prod.
As the paths to js files are already correct, I just give it a try to change my calling .js file to another directly and change the root path and that worked.
Try changing the path of your .js file to another directory.
If someone around still have this issue as I had. Try adding this line of code to your header.
<base href="/" />
It will align your html file to the static directory on Nodejs you are setting.

jQuery requests on mobile application not working

I am making a mobile application using Intel XDK for Android devices, I have been using an emulator and my local development server (127.0.0.1) to test my PHP code. I have been contacting my server using the following ways $.ajax(), $.post() and $.get(). I then decided that I'd reached a suitable point where I should build the application APK file, push the PHP source on to a online website and test it through a proper mobile. So I did, I made the database by exporting my current data from PMA then changed all the URLs in all my requests to point to the right place and pushed my PHP source to the FTP. I then tested my application and was quite shocked by the results.
Error #1:
PHP Fatal error: Can't use function return value in write context in
/home/scrifalr/public_html/sm/api/v1/modules/register/register.php on
line 9
What I did to fix:
I checked the source and apparently after changing this !empty(trim($_POST['username'])) to empty($_POST['username']) seemed to fix that error.
So question one. Why did this error not show up on my local server and not tell me then that I can't do that?
Error #2:
I have a login/register which sends requests which all works, I changed the above PHP and they started to work. However I have a logout page which doesn't seem to work, the code is shown below:
logout.html
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/styles.css">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="intelxdk.js"></script>
<script src="cordova.js"></script>
<script src="xhr.js"></script>
<script src="js/libs/app.js"></script>
<script src="js/libs/functions.js"></script>
<script src="js/logout.js"></script>
<title>Logout</title>
</head>
<body>
</body>
</html>
As you can see, it has nothing besides the includes. The following file is the JavaScript file:
logout.js
window.onload = function () {
getSessionData();
$.post(
"http://sm.script47.net/api/v1/modules/logout/logout.php", {
"userID": window.userID
}, function (data) {
alert(data);
if (data == 1) {
document.location.href = "index.html";
} else {
showTimedMessage(data, "error", 4000);
}
}
);
};
As you can see, it contains the post request and a function called getSessionData(), so after what seemed like an age of trying to debug I came to the conclusion that it is getSessionData() which is failing which again seems odd as it was working in the emulator and all the paths to the requested files are correct. Just for those who would like to see that function:
window.token = null;
window.userID = null;
window.username = null;
window.emailAddress = null;
window.IP = null;
function getSessionData() {
$.ajax({
url: 'http://sm.script47.net/api/v1/modules/sessionData/sessionData.php',
"type": "GET",
dataType: "json",
async: false // This comment is not in the code, I know I shouldn't have this I'm using it for now and it works with it like this.
}).done(function (data) {
window.token = data.token;
window.userID = data.userID;
window.username = data.username;
window.emailAddress = data.emailAddress;
});
}
So question two is that how come even after I tested it thoroughly and ensured that all the paths are correct and uploaded the exact same code, why are some requests being sent e.g. login, register yet others (logout) not working?
After some more debugging it turned out the AJAX call was failing because synchronous AJAX calls are not allowed.

Categories