perl cgi talks to javascript - javascript

I want to retrieve a csv file from one online database. However, due to some XSS issues, I cant directly use ajax, but need to relay on a perl-cgi file.
I already had a working perl-cgi file that can query the csv file , and write the content of the file into a perl variable called $text. Here are some code snippets:
#!/usr/bin/perl
use strict;
use CGI;
use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
# construct cgi object
my $q = CGI->new;
# create a post request
my $useragent = LWP::UserAgent->new();
my $request = POST '.....', [
#something goes here
];
my $response = $useragent->request($request);
my $text = $response->content;
print $text;
I have some general ideas of what to do next, but not so sure about the details. I will upload this perl-cgi file to the server that hosts my website, to the folder called cgi-bin. I just wonder how can I call that perl-cgi file from javascript, and write back the content of $text into javascript varaiable.
Thanks for the help

Javascript is a client-side language, while Perl is a server-side language. This means that you won't be able to directly read the value of a Perl variable into Javascript.
What you can do is have the Perl script output the results of its operations. Your Javascript then calls this Perl script via AJAX and reads the result.
Here's some pseudocode to illustrate what I mean:
Perl script: csv_worker.cgi
// retrieve csv file into $text as per OP
print "Content-type: text/csv\n\n";
print $text;
Javascript
function request() {
var xmlhttp;
if (window.XMLHttpRequest) {
// Supports newer browsers
xmlhttp=new XMLHttpRequest();
} else {
// Supports older IE versions (IE 5/IE 6)
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("result").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","csv_worker.cgi",true);
xmlhttp.send();
}

Related

How do i post variables inside a .js file to a php file without including jquery?

I'm abit confused as to how i will go about doing this, so i'm making a .js file to collect data on a page(100% with js) and i want to POST it to a php file which will then take care of it and insert it into the db etc..
How will i go about doing this? I know you can use jquery in a html document, but i want to use it in a .js file not a .html file.
I've successfully done it using a .html file and importing the jquery file, but i want to do it all in a .js file.
Any help is greatly appreciated. Thank you very much (:
I'd comment, but I can't. Can you post some samples of your code?
What I got is that you are using JavaScript (jQuery) to POST (form data?) over to a PHP file. If you want to use jQuery inside of a .js file, all you have to do is include the jQuery library before you include your .js file, like so:
<script src="jquery.js"></script>
<script src="myExternalScript.js"></script>
And then, inside of myExternalScript.js, you can use jQuery methods.
The external script is aware of your DOM elements, really, just like inline JavaScript would be, so you can still do whatever you want with your form or wherever you are getting the data to POST from.
EDIT: (in accordance to what you commented on this answer)
EDIT 2: I had forgotten to add the request header for POST
If you want to send an AJAX POST request (notice that I set the Content-Type request header, so that the data gets sent correctly):
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","http://zegita.tk/stargazer/magic.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("n="+user);
If you want to send an AJAX GET request:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://zegita.tk/stargazer/magic.php?n="+user, true);
xmlhttp.send();
It is important that you use the correct method, depending on whether you are using $_GET or $_POST in your magic.php file.
Clicking on the button runs this SCRIPT (which further passes 3 JS-variables to the abc.php)
<script type="text/javascript">
function sendJSValsToPHP(){
var xmlhttp;
//These are the variables i am going to post to illustrate the example, what you want
var var_1toPost = 1;
var var_2toPost = 2;
var var_3toPost = 3;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//You can get the response text from abc.php file and process it in any of the tags you want by javascript code
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","abc.php?recieve_1="+var_1toPost+"&recieve_2="+var_2toPost+"&recieve_3="+var_3toPost,true);
xmlhttp.send();
}
</script>
The echo'ed data in abc.php will come in the div="myDiv" //as a response.
<body>
<div id="myDiv" style="border: 1px solid BLUE; height: 100px;">
the things echo'ed in abc.php will come in this div
</div>
<button onclick="sendJSValsToPHP();">Click Me To Send JS-Values to abc.php</button>
</body>
and then in abc.php //file
<?php
$recieved_1 = $_GET['recieve_1'];
$recieved_2 = $_GET['recieve_2'];
$recieved_3 = $_GET['recieve_3'];
//Do your processing here and insert it in the database
//Insert Query OR Update Query (whatever)
// after you have inserted you can get the response in
// the <div> having id="myDiv" Or whatever you want
// Suppose you have successfully inserted data then
$insertedDataBoolean = true;
if($insertedDataBoolean){
echo "Data: " . $recieved_1 . ", " . $recieved_2 .
" and " . $recieved_3 . " inserted successfully.";
}
else{
echo "Data-insertion error.";
}
?>

Get the link of an specific xml file from the server (php script) and load it in javascript

In the web site I am creating a user can upload and download files and I create an xml log with operation informations.
In the website there is a page where a table of the log xml is created reading the xml.
It worked fine when it was all in my hard disk but now that I started hosting it on a server I don't know how to make it work.
In local computer the xml request was
xmlhttp.open("GET","file.xml",false);
Now in the real web site I need to make an ajax call to a php script to geth the path of my personal xml file.
First question: what kind of address i need to output from the php script?
http://mywebsite/folder1/folder2/log_username.xml
Is something like this?
With the ajax call I save the address in a variable and the xml request became:
xmlhttp.open("GET",xml_address_variable,false);
The problem is that the XML isn't loaded. Where is the problem?
EDITED: now that i wrote in the javascript code the path of a specific user for experiment it worked, but if I put the variable (link_xml) where the AJAX call should save the path it doesn't work so this is the critical part of my code:
var link_xml = askXMLaddress();
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",link_xml,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
for ajax to load it you'd need a file path from your doc-root. so if you want
http://mywebsite/folder1/folder2/log_username.xml
all JS needs is
../folder1/folder2/log_username.xml
then you can use jquery.load() like so
var path = <?php echo "../folder1/folder2/log_username.xml"; ?>;
$( "#username" ).load(path);
now instead of that 'php echo...' stuff you'd probably do better to use another ajax request. BUT that will depend on your use case.
function loadXML(path, selector)
{
var xml = new XMLHttpRequest();
try {
xml.open("GET", path, false);
xml.send(null);
}
catch (e) {
//some error stuff
}
document.getElementById(selector).innerHTML=xml.responseText;
}
I can't guarentee this works I don't have a server parsing xml stuff at the moment.

Creating an XML file using Javascript

I have the following code:
xmlDoc=loadXMLDoc("dbbackup.xml");
x=xmlDoc.getElementsByTagName("record");
alert(x);
for (i=0;i<3;i++) {
newel=xmlDoc.createElement("edition");
newtext=xmlDoc.createTextNode("first");
alert("x : "+x[i]);
alert("newtext :"+newtext.nodevalue);
x[i].appendChild(newel);
alert("sd");
}
function loadXMLDoc(dname) {
if (window.XMLHttpRequest) {
xhttp=new XMLHttpRequest();
} else {
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
I have created dbbackup.xml in the same location and the XML file looks like:
<sticky>
<record></record>
</sticky>
But after running my script the xml file is not getting updated.
Javascript cannot modify files on disk, it only runs for the client in the client's web browser.
To actually write to and from files on a server, you have to use server-side languages and technologies, like PHP or ASP.
I made this - making XML at client side then using everyday praksis
Mike
function makeSlot() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) showBon(); }
xmlhttp.open("POST","crMakeSlot.php",true);
xmlhttp.send(wrapUp());
}
/***
* make the final transaction - using XML
*/
function wrapUp () {
var transaction = document.implementation.createDocument("","", null);
var operator = document.createElement("operator");
var textblok1 = document.createTextNode(document.getElementById("rText").value);
operator.appendChild(textblok1);
var root = document.createElement("transaction");
root.setAttribute("tstamp", now);
root.setAttribute("sequenceno", zSequenceNo.textContent);
if (parseInt(document.getElementById("zDankort").value) > 0) root.setAttribute("dankort", document.getElementById("zDankort").value);
if (parseInt(document.getElementById("zCash").value) > 0) root.setAttribute("cash", document.getElementById("zCash").value);
if (parseInt(document.getElementById("zCredit").value) > 0) root.setAttribute("credit", document.getElementById("zCredit").value);
if (parseInt(document.getElementById("zCheck").value) > 0) root.setAttribute("check", document.getElementById("zCheck").value);
if (parseInt(document.getElementById("zGiftcard").value) > 0) root.setAttribute("giftcard", document.getElementById("zGiftcard").value);
if (parseInt(document.getElementById("zVoucher").value) > 0) root.setAttribute("voucher", document.getElementById("zVoucher").value);
root.appendChild(operator);
var divObj = document.getElementsByTagName("div");
/***
* when column value is 4, then we have our data complete - next cycle
*/
for (ix = 0; ix < divObj.length; ix++) {
switch (divObj[ix].getAttribute("column")) {
case "1": var row = document.createElement("row"); row.setAttribute("item",divObj[ix].textContent);
case "2": row.setAttribute("price",divObj[ix].textContent);
case "3": row.setAttribute("quantum",divObj[ix].textContent);
case "4": root.appendChild(row);
default: break;
}
}
transaction.appendChild(root);
return(transaction);
}
SomeKidWithHTML is right.
JavaScript is designed to only modify a file, in memory, that is loaded inside a browser framework.
Think of the browser as a sandbox that your kids (html, xml, etc.) can play in. As long as Johnny (xml) is in the sandbox playing, all is well. But if Johnny were allowed to play outside of that sandbox, just think of the havoc that could be done on your machine by websites.
There is NO WAY a JavaScript can permanentally affect a file on your local machine, by itself. It can only play inside the sandbox (locally, it can make calls to Java, or an other API, to affect change, but that's a whole other deal).
JavaScript is client side only. If you expect it to affect a server, it can only do it through calls back to the server. At the server you will need some kind of programming (asp.net, java, php, html, others) to receive and answer that call and do something with it.
JavaScript, by itself, is very powerful... but only inisde the sandbox (browser). For it to affect anything else outside of that browser it must depend on other programs already in place and ready to receive those requests.
And this is all in the name of security, mostly.
You can collect data from the web page in client side and send them to the server (ajax), which will then generate the xml file and send back a link to the file (ajax). Use javascript to generate a download link using the link returned by the server.
This is the way I do to solve the problem in one of my project.

How to read variables comma separated varibals from a text file into a javascript array?

I want to read text file's comma separated variables in a java script array
right now i have hard coded values like this
var arrUserTags = new Array('{{Name}}','{{Address}}','{{Company}}');
but i want to read it from a text file dynamically on page load
how can i read it?
I am done with below solution but now i am facing 1 more problem.
When i do changes to text file that don't become effective, while the browser takes the old values only? How to sort it out?
You need AJAX to load the file:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", path, true);
xmlhttp.send();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
parse(xmlhttp.responseText);
}
}
And then Split the text:
function parse (text) {
var array = text.split(",");
//Do something
}
You can not use Javascript (not talking about server-side js such as node.js) to read local file system files due to security reasons, you can do so with some server-side language such as PHP, JSP, etc.

How can I access the plain text loaded in an <iframe> on IE?

I have an <iframe> whose src points to a plain text file (not HTML). The text gets loaded and displayed on screen, but seems to be hidden to JavaScript.
In other browsers, iframe.contentWindow.document.body.innerText is enough to get it for you, but IE returns an empty string in that case.
Is there a way that IE can access the text inside the file without involving a server?
You can read this file using XmlHttpRequest. If the browser can read it, so can XmlHttpRequest.
/* Read a file using xmlhttprequest
If the HTML file with your javascript app has been saved to disk,
this is an easy way to read in a data file. Writing out is
more complicated and requires either an ActiveX object (IE)
or XPCOM (Mozilla).
fname - relative path to the file
callback - function to call with file text
*/
function readFileHttp(fname, callback) {
xmlhttp = getXmlHttp();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", fname, true);
xmlhttp.send(null);
}
/*
Return a cross-browser xmlhttp request object
*/
function getXmlHttp() {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp == null) {
alert("Your browser does not support XMLHTTP.");
}
return xmlhttp;
}
Call the readFileHttp(fname, callback) using the iframe.src property for the fname parameter.
The callback parameter should be a function that does whatever you want with the result.
Something like this:
var myIFrame = document.getElementById('iframeIdGoesHere');
readFileHttp(myIFrame.src, function(result){
//process the result
});
EDIT based on comment and edit in question:
It might be that body is not available as a js property on the document. You could try:
iframe.contentWindow.document.getElementsByTagName('body')[0].innerText
My original answer (kept only as reference because of the comment):
You
say in a comment that you pull the
path from an <input type='file' />.
You can use that to upload the file to
the server, and then read it using
simple file reading mechanisms. (after
all, the <input type='file' /> is
meant for server uploads...)
Just a shot in the dark, but have you tried the innerHTML property?
Alternatively, the more "proper" way to do this is to request the file directly with XMLHttpRequest.
and
window.frames[0].document.getElementsByTagName("body")[0].innerHTML
?

Categories

Resources