JSONP - express: Why does the browser ignore the request? - ajax

I wrote the following HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML page</title>
</head>
<body>
<script src='http://localhost:3000?callback=mycallbackFunction'> </script>
<script>
function mycallbackFunction(data) {
alert('here');
alert (data['a']);
}
</script>
</body>
</html>
As you can see, the script tag includes a JSONP request to a remote server.
In addition, I wrote the following node.js file and ran it as a server:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.jsonp({'a': 'blabla'});
});
app.listen(3000);
After I had run the node.js file and opened the browser with the html page, I expected to see a pop-up window of alert. But, no. I didn't see anything.
The Network Tab in Developer Tools shows that the request has been accepted:
Do you know how to resolve it?

You need to swap the order of your <script> elements.
Explanation:
Express is correctly serving a script that looks like myCallbackFunction({'a': 'blabla'}), which is exactly what you hoped for. However, this script runs immediately, and myCallbackFunction has yet to be defined, so nothing happens. Then, in the next <script> block, you define myCallbackFunction, but this is useless, since the (failed) call has already happened in the previous <script>.
Also, you have a case mismatch on the C in mycallbackFunction -- make sure the capitalization agrees between the callback parameter and the name of your function.

The solution is to switch the order of both script tags:
<body>
<script>
function mycallbackFunction(data) {
alert('here');
alert (data['a']);
}
</script>
<script src='http://localhost:3000?callback=mycallbackFunction'> </script>
</body>

Related

Why does the browser tell me the parse is not defined even if I have imported it in the head of the HTML file?

I'm trying to connect my HTML files with the parser server. I followed the direction of the back4app guides and added the following code to the head of index.html. But the browser kept telling me Parse is not defined.
<script src="https://npmcdn.com/parse/dist/parse.min.js"></script>
<script type="text/javascript">
Parse.serverURL = "https://parseapi.back4app.com";
Parse.initialize(
"MY_APP_ID",
"MY_JS_KEY"
);
</script>
Can you please test the code below?
<script src="https://cdnjs.cloudflare.com/ajax/libs/parse/2.1.0/parse.js"></script>
<script type="text/javascript">
function myFunction() {
Parse.initialize("APP_ID", "JS_KEY");
Parse.serverURL = 'https://parseapi.back4app.com/';
}
/</script>

p5 setVoice not working

while trying to change the voices in the p5.speech, setVoice function just not working at all...
I've been tried both string and index, but still went wrong, is there anyone can help? I would be really appreciated!!
Thanks!
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.5/p5.min.js">
</script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.5/addons/p5.dom.js">
</script>
<script src="p5.speech.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<button id='talks'>
click to talk
</button>
<script>
$('#talks').click(function(){
console.log('hi')
var talk= new p5.Speech()
talk.onLoad=Voices
function Voices(){
talk.listVoices()
talk.setVoice('Google UK English Male')
}
talk.speak("What's up")}
</script>
</body>
</html>
below is the output of talk.listVoices() :
enter image description here
Firstly my answer is not the full solution, but there are some simple SyntaxErrors in your example. Thats why it's not runable for me at all.
You are opening click( but didn't close it, for better clearance i reformatted your code and added the closing bracket.
A function normally get's called with brackets, so it should be Voices();
This is not necessary for every Browser, but normally an ending line in JavaScript get's an ;
$('#talks').click(
function(){
console.log('hi');
var talk= new p5.Speech();
talk.onLoad=Voices();
function Voices(){
talk.listVoices();
talk.setVoice('Google UK English Male');
}
talk.speak("What's up");
}
)
With that changes i get an console output like this:
VM43:3: hi
p5.speech.js:136 p5.Speech: voices not loaded yet!
p5.speech.js:89 p5.Speech: voices loaded!

Cannot print this document yet, it is still being loaded - Firefox Printer Error

My API generates dynamic HTML document and dumps it into a popup window like so:
var popup = window.open('', "_blank", 'toolbar=0,location=0,menubar=1,scrollbars=1');
popup.document.write(result);
After the document is reviewed by a user, they can print it calling
window.print();
Chrome handles it without any problems, but Firefox shows a Printer error:
"Cannot print this document yet, it is still being loaded"
Printer window opens only if I hit Ctrl+R.
It appears that $(document).ready() never happens in firefox and it keeps waiting for something to load.
Status bar in popup says Read fonts.gstatic.com
Here's a brief content of a document:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="https://fonts.googleapis.com/css?family=Orbitron|Jura|Prompt" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<title>Invoice #15001</title>
<style>
...
</style>
</head>
<body>
<div id="invoice_body" >
...
</div><!-- Invoice body -->
</body>
</html>
I have a feeling it has something to do with Google fonts. Any help is appreciated
When you pass "" as the URL to window.open, Firefox loads 'about:blank' at which point script security is likely preventing you from pulling in external resources via http or https ...
I am able to reproduce your problem and have it popup with the same error when I try to print-- I was able to get it working by using a data url when calling window.open ...
Based on your example, result is a string containing the HTML for the popup, so you would call window.open like this, and no longer use document.write for anything:
var popup = window.open("data:text/html;charset=utf-8,"+result, "printPopup", "toolbar=0,location=0,menubar=0,scrollbars=1");
I tested this with result being a string containing:
<html><head>
<link rel="stylesheet"href="https://fonts.googleapis.com/css?family=Tangerine">
<style> body { font-family: 'Tangerine', serif; font-size: 48px; } </style>
<title>Test</title></head>
<body>
<div>Testing testing</div>
<div>Print</div>
</body>
</html>
And clicking the print link worked as expected...
I had to go an extra mile, but:
I added server side code that would save a html file and pass a link to that file instead of html content:
ob_start();
include('ezts_invoice_template.php');
$dom = ob_get_clean();
$ezts_file_path = EZTS_PLUGIN_PATH.'kernel/tmp/'.session_id().'_tmp.html';
$ezts_file = fopen($ezts_file_path, 'w+');
$result = fwrite($ezts_file, $dom);
fclose($ezts_file);
print_r('{"result":"success", "file":"'.plugin_dir_url(__FILE__).'tmp/'.session_id().'_tmp.html"}');
in JS I open a popup by a link passed from PHP:
var popup = window.open(result.file, "_blank", 'toolbar=0,location=0,menubar=0,scrollbars=1');
and, finally, in template file I added event listener to request deletion of temporary file when the window is closed
window.addEventListener('beforeunload', function(event) {
window.opener.eztsApiRequest('deleteTempFile',
'',
function(result, status){ console.log(result); });
}, false);
It's not as easy, but it works great.

mikrotik add hotspot user from javascript API

I try to develop an app to create user in mikrotik user manager via api. And I also tried JavaScript in the terminal by using following command:
$node script name.js
That is working and a user created.
Then I tried to run that JavaScript by on click html button. Then JavaScript doesn't run and no user crated. Code follows:
<html>
<head>
</head>
<body>
<button type = "button" onclick="conn();">Try it</button>
<script type="text/javascript">
var api = require('mikronode');
var connection = new api('192.168.5.1','admin','xxxxxx');
connection.connect(function conn() {
conn.closeOnDone(true); // All channels need to complete before the connection will close.
var actionChannel=conn.openChannel();
// These will run synchronsously
actionChannel.write(['/tool/user-manager/user/add','=username=tiran','=password=123456','=customer=admin']); // don't care to do anything after it's done.
actionChannel.write(['/tool/user-manager/user/create-and-activate-profile','=customer=admin','=numbers=tiran','=profile=general']); // don't care to do anything after it's done.
//actionChannel.write('/tool/user-manager/user/print',function(chan) {
//chan.on('done',function(data) {
//packets=api.parseItems(data);
//packets.forEach(function(packet) {
//alert('done');
//alert('user: '+JSON.stringify(packet));
//console.log('user: '+JSON.stringify(packet));
//});
//listenChannel.close(); // This should call the /cancel command to stop the listen.
//});
//});
actionChannel.close(); // The above commands will complete before this is closed.
});
</script>
</body>
</html>
That code is for NodeJS, you cannot run in directly on the browser as JavaScript

DOM onLoad event without jquery

HTML code :
<html>
<head>
</head>
<body>
<script type="text/javascript" src="/js/colorbook.js"></script>
<script type="text/javascript">
book.init();
</script>
</body>
</html>
JS code :
var book = (function(){
init = function(){
console.log ( "initialized")
}return init();
}());
Question : The above code works. But I am unable to understand how?. Can any of JS guys help me here or guide me how should I start debug this code to understand it.
Ok so as per your comment. The Javascript you have there is all executed sequentially as the browser reads it from the incoming data stream. That being said, All javascript contained within the first script tag will be executed. Then the second script tag will be executed in sequence as well.
So right now you can look at the book.init() as being the last provided javascript call to be executed.
I tried your JS code in jsfiddle and could not get it to work check This Fiddle to see what I mean.
What is happening in your JS code is the last () at the end of the var book declaration executes the anonymous function which will print the line to the console. However from the code you supplied the book variable never gets a book.init() method. So once that call is reached it will throw an error of undefined.

Resources