Can't find server side Perl script - javascript

I am running Mopidy on a Raspberry Pi with the latest Raspbian Wheezy.
I am trying to call a server side Perl script from Javascript like this:
var addToPlaylist = function() {
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", "addToPlaylist.pl?uri=" + encodeURI("testuri") + "&&name=" + encodeURI("testname"), true);
xmlHttpRequest.send();
}
But I get the error:
POST http://192.168.0.10:6680/addToPlaylist.pl?uri=testuri&&name=testname 404 (Not Found)
However, if I navigate my browser to:
http://192.168.0.10:6680/addToPlaylist.pl
I can see the script in plain text.
I have tried moving the file to where Mopidy gets it's Javascript files from and to various other places, and the file has a full set of permissions.
Is this likely to be something Mopidy specific or is this a general web server thing? Obviously I don't want to be able to access the R-Pi's whole file system, so is there somewhere where I need to whitelist what can be seen from the client? I am new to Javascript and Web Servers so I do not know the terminology to search for. Could you point me in the right direction?
Thanks

You need to run something that can run Perl scripts, e.g. Perl Dancer, on another port.

Related

XMLHttpRequest is not defined

I have a server using node and express. I'm building the client app. It's supposed to get data from the server like so:
let req = new XMLHTTPRequest();
req.open('GET', 'localhost:5000/newarticle');
req.onload = function() {
let data = JSON.parse(req.responseText);
renderHTML(data);
}
req.send();
This code is part of a main.js file which is linked to my index.html file. The index.html file is served by express to the client when they access the website. On index.html, there's a button, with functionality associated with the onclick event that's defined in main.js. So far, so good. But when the button is clicked, I get a console message in the browser reading "XMLHttpRequest is not defined."
My understanding is that the browser (Chrome/V8) and node are separate JavaScript environments. Things like XMlHttpRequest, which are defined in node, are not defined in V8.
This is confusing to me. No tutorial I find on how to use AJAX mentions this as an issue. I haven't been able to find a source that digs into how I can serve up an HTML + javascript page that allows the user to send AJAX requests back to the server that addresses this issue. Honestly, I don't even know quite what to search for to try and find an explanation for this set of issues. Any advice or links would be very appreciated!

Write to text file with javascript on GoDaddy server

I have tried numerous different codes that I have found here along with the following code below I got from learn.microsoft.com. They all give me the same error though. The error I get is "ActiveXObject is not defined". Can someone please tell me how to fix this issue. How do I define the object or is this yet another problem that is related to my host, GoDaddy?!?!
This is for a Plesk/Windows server hosted by GoDaddy.
This is a link is to just one of the codes from stackoverflow that I have tried: Use JavaScript to write to text file?
Microsoft Code
<script>
var fso, tf;
fso = new ActiveXObject("Scripting.FileSystemObject");
tf = fso.CreateTextFile("G:\mysite\file.txt", true);
// Write a line with a newline character.
tf.WriteLine("Testing 1, 2, 3.") ;
// Write three newline characters to the file.
tf.WriteBlankLines(3) ;
// Write a line.
tf.Write ("This is a test.");
tf.Close();
</script>
You can't write to a file on the server with client-side JavaScript (if clients could write arbitrary files on servers then Google's homepage would be vandalised every second).
The code you've found could write to the hard disk of the computer the "page" was loaded on, but only if the "page" was an HTA application and not a web page.
The standard way to send data to an HTTP server from JavaScript is to make an HTTP request. You can do this with an Ajax API like fetch.
You then need a server-side program (written in the language of your choice) that will process the request and write to the file (although due to race conditions, you are normally better off using a database than a flat file).

call Perl script from javascript using AJAX

I want to call a perl script from javascript. I have tried this using AJAX:
function create_request(obj) {
var req = \"id=\"+0;
var req_http =new XMLHttpRequest();
req_http.open(\"POST\", \"create_file.pl\", false);
req_http.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");
req_http.send(req);
req_http.onreadystatechange = function() {
if (req_http.readyState == 4) {
var resp=req_http.responseText;
document.write(resp); // *** echoes the content of create_file.pl
}
}
}
create_file.pl:
#!/usr/bin/perl
#
#
use strict;
use warnings;
use CGI;
my $cgi = CGI->new;
open FILE, ">>file.txt" or die $!;
print FILE "aaa";
close(FILE);
print $cgi->header('text/plain;charset=UTF-8');
print 0;
The perl script only creates a text file.
After javascript calls the perl script, the print of the returned result is the entire content of create_file.pl, and the file file.txt it is not created.
This has nothing to do with AJAX
If you are getting the contents of your perl file returned from your AJAX call, what this means is that your web server is not configured to handle perl (Javascript is accessing the location correctly, or you'd get a 404).
As for how to do this, without knowing your server it's hard to say. Usually you need to set up a rule to pass requests to .pl files through to your CGI handler.
In lighttpd (what I use), that's:
$HTTP["url"] =~ "/cgi-bin/" {
cgi.assign = ( ".pl" => "/usr/bin/perl" )
}
If you're not using lighttpd, I'd suggest taking a Google for your-server cgi and following the instructions to configure it to parse those files through perl.
After javascript calls the perl script, the print of the returned result is the entire content of create_file.pl, and the file file.txt it is not created.
Then either:
You are working on a local file system instead of through a webserver or
You have not configured your server to treat the Perl program as CGI instead of a static file.
When you receive the text of a Perl script back from your web server, and you were expecting the web server to execute the script, then what you have is misconfigured web server.
You need to configure your web server so that it knows to execute files.
Typically one separates one's executables from one's static content. and then configures the web server to allow execution of the programs in the executables directory. The exact syntax of that configuration will depend on which web server you're running.

Difference in *.JS files opened with cURL and in Browser

If I open this .JS file (link text) in Browser I get back following in browser window:
var PHONE_CNT=2;var PHONE_CNT2=0;var PHONE_CNT3=0;var EMAIL_CNT=2;var SHOW_CNT=1795;var PH_c="";var PH_1=0;var PH_2=0;var PH_3=0;
PH_1 = "JUQyJUFCJThDJUM5JThFJUQzJTgzeSVDMiVEQyVCQ2ElQkUlREQlQzglOUUlOTR6JUE2bSVCN3ElOUIlRTglQzQlQkYlODUlRDklQjIlQzglQjclQUE=";
If I open the same file using cURL or ?php (file_get_contents) then the content differs:
var PHONE_CNT=0;var PHONE_CNT2=0;var PHONE_CNT3=0;var EMAIL_CNT=0;var SHOW_CNT=1;var PH_c="";var PH_1=0;var PH_2=0;var PH_3=0;
PH_1 = "JUQyJUFCJThDJUM5JThGJUMyJTg0JTlBJUJBJUM3JUJEdSVDMCVDRCVDOCVFNSU4RiU3RiVBNiVBOSVCOCU4MyU5MCVEOA==";
The difference is PH_1 value.
I tried to set different options for cURL but nothing helps. Any idea how to get .JS file content using cURL same as what I get when using browser.
Thank you in advace.
The server must be generating a different PH1 value based on some request parameters. You'll have to trace out the HTTP headers from both requests to see what causes the difference, e.g. setting up a local proxy such as http://www.fiddler2.com/fiddler2/ and making both requests through that.
It could be some combination of the user agent, accepts headers, cookies or the IP or country you're connecting from that's makign the difference - without knowing what the server logic is (or understanding what the different PH1 values mean) we can't really help you sorry.
Curl just gets the data from the server, it does not interpret javascript. If you want to interpret the javascript from the webpage, you'll have to use a javascript engine as spidermonkey.

Generate some xml in javascript, prompt user to save it

I'd like to make an XML document in JavaScript then have a save dialog appear.
It's OK if they have to click before the save can occur.
It's *not* OK if I *have* to use IE to achieve this (I don't even need to support it at all). However, Windows is a required platform (so Firefox or Chrome are the preferred browsers if I can only do this in one browser).
It's *not* OK if I need a web server. But conversely, I don't want to require the JavaScript to be run on a local file only, i.e. elevated privileges -- if possible. That is, I'd like to to run locally or on a *static* host. But just locally is OK.
It's OK to have to bend over backwards to do this. The file won't be very big, but internet access might either be there, be spotty or just not be a possibility at all -- see (3).
So far the only ideas I have seen are to save the XML to an iframe and save that document -- but it seems that you can only do this in IE? Also, that I could construct a data URI and place that in a link. My fear here is that it will just open the XML file in the window, rather than prompt the user to save it.
I know that if I require the JavaScript to be local, I can raise privileges and just directly save the file (or hopefully cause a save dialog box to appear). However, I'd much prefer a solution where I do not require raised privileges (even a Firefox 3.6 only solution).
I apologize if this offends anyone's sensibilities (for example, not supporting every browser). I basically want to write an offline application and Javascript/HTML/CSS seem to be the best candidate considering the complexity of the requirements and the time available. However, I have this single requirement of being able to save data that must be overcome before I can choose this line of development.
How about this downloadify script?
Which is based on Flash and jQuery, which can prompt you dialog box to save file in your computer.
Downloadify.create('downloadify',{
filename: function(){
return document.getElementById('filename').value;
},
data: function(){
return document.getElementById('data').value;
},
onComplete: function(){
alert('Your File Has Been Saved!');
},
onCancel: function(){
alert('You have cancelled the saving of this file.');
},
onError: function(){
alert('You must put something in the File Contents or there will be nothing to save!');
},
swf: 'media/downloadify.swf',
downloadImage: 'images/download.png',
width: 100,
height: 30,
transparent: true,
append: false
});
Using a base64 encoded data URI, this is possible with only html & js. What you can do is encode the data that you want to save (in your case, a string of XML data) into base64, using a js library like jquery-base64 by carlo. Then put the encoded string into a link, and add your link to the DOM.
Example using the library I mentioned (as well as jquery):
<html>
<head>
<title>Example</title>
</head>
<body>
<script>
//include jquery and jquery-base64 here (or whatever library you want to use)
document.write('click to make save dialog');
</script>
</body>
</html>
...and remember to make the content-type something like application/octet-stream so the browser doesn't try to open it.
Warning: some older IE versions don't support base64, but you said that didn't matter, so this should work fine for you.
Without any more insight into your specific requirements, I would not recommend a pure Javascript/HTML solution. From a user perspective you would probably get the best results writing a native application. However if it will be faster to use Javascript/HTML, I recommend using a local application hosting a lightweight web server to serve up your content. That way you can cleanly handle the file saving server-side while focusing the bulk of your effort on the front-end application.
You can code up a web server in - for example - Python or Ruby using very few lines of code and without 3rd party libraries. For example, see:
Making a simple web server in python
WEBrick - Writing a custom servlet
python-trick-really-little-http-server - This one is really simple, and will easily let you server up all of your HTML/CSS/JS files:
"""
Serves files out of its current directory.
Doesn't handle POST requests.
"""
import SocketServer
import SimpleHTTPServer
PORT = 8080
def move():
""" sample function to be called via a URL"""
return 'hi'
class CustomHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
#Sample values in self for URL: http://localhost:8080/jsxmlrpc-0.3/
#self.path '/jsxmlrpc-0.3/'
#self.raw_requestline 'GET /jsxmlrpc-0.3/ HTTP/1.1rn'
#self.client_address ('127.0.0.1', 3727)
if self.path=='/move':
#This URL will trigger our sample function and send what it returns back to the browser
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(move()) #call sample function here
return
else:
#serve files, and directory listings by following self.path from
#current working directory
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
httpd = SocketServer.ThreadingTCPServer(('localhost', PORT),CustomHandler)
print "serving at port", PORT
httpd.serve_forever()
Finally - Depending on who will be using your application, you also have the option of compiling a Python program into a Frozen Binary so the end user does not have to have Python installed on their machine.
Javascript is not allowed to write to a local machine. Your question is similar to this one.
I suggest creating a simple desktop app.
Is localhost PHP server ok? Web traditionally can't save to hard drive because of security concerns. PHP can push files though it requires a server.
Print to PDF plugins are available for available for all browsers. Install once, print to PDF forever. Then, you can use a javascript or Flash to call a Print function.
Also, if you are developing for an environment where internet access is spotty, conwider using VB.NET or some other desktop language.
EDIT:
You can use the browser's Print function.
Are you looking for something like this?
If PHP is ok, if would be much easier.
With IE you could use document.execCommand, but I note that IE is not an option.
Here's something that looks like it might help, although it will not prompt with SaveAs dialog, https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FOL.
One simple but odd way to do this that doesn't require any Flash is to create an <a/> with a data URI for its href. This even has pretty good cross-browser support, although for IE it must be at least version 8 and the URI must be < 32k. It looks like someone else on SO has more to say on the topic.
Why not use a hybrid flash for client and some server solution server-side. Most people have flash so you can default to client side to conserve resources on the server.

Categories