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.
Related
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).
When I put the script directly in the .PHP file my script works perfectly:
function setup()
{
var setRows = <?php if(!isset($_GET['rows']))echo 3;else echo $_GET['rows']; ?>;
var setColumns = <?php if(!isset($_GET['columns']))echo 3;else echo $_GET['columns']; ?>;
document.getElementById('rows').value = setRows;
document.getElementById('columns').value = setColumns;
document.getElementById('rowOutputId').value = setRows;
document.getElementById('colOutputId').value = setColumns;
}
However, when I put it in a separate file and link it, it prints out the literal string instead of the correct value. So like this:
<script type="text/javascript" src="js/file.js"></script>
It echoes the following:
<?php if(!isset($_GET['rows']))echo 3;else echo $_GET['rows']; ?>
Also, it's important to note that when I have it directly in the HTML file it stores the PHP perfectly without the quotes around it, but in the separate file it gives me the following error if I take away the quotes:
Uncaught SyntaxError: Unexpected token <
Your server decides what to do with a request based on its extension (this is an over-simplification, but will do for now).
Your server has been configured to treat files ending on .php as a php file. This means, that when you request this file from Apache, Nginx, or whatever webserver software you are using, your webserver will first ask the php software to parse and execute it. When the PHP software executes the first code, it will run anything between <?php and ?> . It will then return the result of the code execution to your webserver, which will pass it back to the client.
However, when your browser loads the .js file, your webserver considers this as a "normal" file. It will then read the file and return it straight to the client, without passing it to the PHP software first. Therefore, nothing will be executed or interpreted, and you will simply see all the text in the file.
Now assume you put PHP code in your .js file. It wasn't executed, and therefore the PHP code will still be present when your browser receives the response from the webserver. Your browser will then try to parse and execute the javascript in the file, but your <?php tag isn't valid javascript. Therefore, attempting to execute this file will cause errors in your browser console.
You can configure which extensions should be treated as PHP code in your webserver config.
For Apache this is done through addHandler, while for nginx this can be done through location directives.
I would strongly advice against changing this to treat javascript as PHP, as your javascript files aren't supposed to contain PHP code. If you want to pass something to a variable, just do it in the HTML code generated by the PHP file.
I am trying to run a script that will run every 5 minutes in a shared hostings wordpress folder that will rename the newest CSV file in that folder.
/wp-content/csv/sample.csv
I tried putting a js file in the folder within that folder and run it.
var fs = require('fs');
function runClear()
{
fs.readdir("", (err, files) => {
files.forEach(file => {
console.log(file);
});
})
}
runClear();
setInterval(runClear, 300*1000);
However, it seems like I got client side and server side scripting confused. It seems like I need node.js.
What would be the best approach for this?
Regards,
Yes you are right you are confused in client side and server side script.
Javascript is a client side script which deal with all the user interactions like what will happen user click something or submit a form, hover over some element, scroll the web page etc.
Where as server side script like php deals with data stored on server like mysql records or the physical files.
what you are trying to do is to change the server resource from client side script. and you can not do that directly.
Instead you can call an ajax function which send an HTTP request to some script placed on server. And in that server script write the code to read the existing files in a directory and rename them using file handling operations.
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.
I have a very simple Python file, called python1.py, whose contents are:
f = open('C:\\Temp\\test.txt', 'w')
f.write('Succeeded')
f.close()
I wish to execute this from JavaScript, like so:
jQuery.ajax({
type: "POST",
url: "/cgi-bin/python1.py",
success: function (msg) {
alert("Data Saved: " + msg);
}
});
However, all that happens is that I get an alert showing me the contents of the Python script. The file C:\Temp\test.txt does not get created, so clearly the Python was not executed.
How do I persuade the code to execute the Python script instead of just reading it?
You simply need to configure your web server to execute your *.py scripts, instead of serving them as plain text.
If you are using Apache as a web server, you need to enable mod_python or mod_wsgi.
EDIT:
Since you are using using Apache, you may want to check the following article, which briefly describes how to set up the mod_python module:
A Brief Introduction to Apache's mod_python Module
You could also use the opensource project Pico. It's a really elegant way of calling server side Python code from client side Javascript.
The author has provided some simple examples here https://github.com/fergalwalsh/pico/wiki/Example-1:-Hello-World
Are you able to execute the script directly from the browser. This looks more like a webserver config issue than jquery's
If your script is that simple, you would be best off using CGI on the server side rather than mod_python or mod_wsgi as suggested by others. For details on how to set up Apache for CGI with Python and simple script examples see:
http://webpython.codepoint.net/cgi_tutorial