I wrote a simple html file with form data and used XMLHttpRequest to post data to another python cgi script, but for some reason, the python script does not do what it is supposed to do. After passing the data from the html to python, the cgi script is supposed to create a text file and write a line into that text file, but the text file is not created after I click the 'Run' button. Any idea why this happened? Here's the html code and python script:
----HTML----
<html>
<head> <title> TEST </title> </head>
<script type="text/javascript">
function run(){
var facPath = document.forms["inputParams"]["FacPath"].value;
var facId = document.forms["inputParams"]["IdName"].value;
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response").innerHTML = this.responseText;
}
};
xhttp.open("POST", "/cgi-bin/processRequest.py", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
xhttp.send("facPath="+facPath+"&facId="+facId);
}
</script>
<body>
<P>
<form name="inputParams" >
Factor File Path <BR>
<input type="text" name="FacPath"> <BR><BR>
Factor ID Name <BR>
<input type="text" name="IdName"> <BR><BR>
<input type="button" value="Run" name="submit" onclick="run()">
</form>
</P>
<div id="response"> </div>
</body>
</html>
----Python cgi script----
import cgi
import sys
form = cgi.FieldStorage()
facPath = form.getvalue('facPath','None')
if facPath:
with open(r'C:\Users\XXX\inputSpec.txt','w') as outputFile:
outputFile.write(facPath)
sys.stdout.write("Status: 200 OK\n")
sys.stdout.write("Content-Type: text/plain\n")
sys.stdout.write("\n")
sys.stdout.write("Success.")
Do I need to make the python script executable? Or is it some other reason? Thank you.
Related
I am trying to set up a simple HTML form, and want the response to be added to the HTML form with xmlhttprequest.
Im new in scripting and does not fully understand the handling of objects
The HTML form:
<form id="frm1" action="./cgi-bin/input.cgi">
WPT: <input type="text" name="wpt1"><br>
Time: <input type="text" name="time1"><br><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>
<p id="demo">RESULT HERE</p>
<script>
function myFunction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "./cgi-bin/input.cgi", true);
xhttp.send();
}
</script>
The cgi code:
#!/usr/bin/python
import cgi, cgitb
cgitb.enable()
data = cgi.FieldStorage()
print("Content-Type: text/html\n")
print("Data: ")
print(data["wpt1"].value)
print(data["time1"].value)
I expect that the string "Data: [wpt1] [time1]" to be located at RESULT HERE, where [wpt1] and [time1] has the values from input data.
The error message is:
=> 12 print(data["wpt1"].value)
data = FieldStorage(None, None, []), ].value = []
My understanding of the error message is that no data is submitted.
When using this code for the script part the input is submitted and printed, but not as a content of the HTML Form.
<script>
function myFunction() {
document.getElementById("frm1").submit();
}
</script>
I think you either use POST or send values as query params. method 1:
<form id="frm1" action="./cgi-bin/input.cgi">
WPT: <input type="text" id="wpt1" name="wpt1"><br>
Time: <input type="text" id="time1" name="time1"><br><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>
<p id="demo">RESULT HERE</p>
<script>
function myFunction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "./cgi-bin/input.cgi?wpt1="+document.getElementById("wpt1").value+"&time1="+document.getElementById("time1").value, true);
xhttp.send();
}
</script>
or method 2:
<form id="frm1" action="./cgi-bin/input.cgi">
WPT: <input type="text" id="wpt1" name="wpt1"><br>
Time: <input type="text" id="time1" name="time1"><br><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>
<p id="demo">RESULT HERE</p>
<script>
function myFunction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "./cgi-bin/input.cgi", true);
xhttp.send(JSON.stringify({"wpt1":document.getElementById("wpt1").value,"time1":document.getElementById("time1").value}));
}
</script>
In my Xampp htdocs file I have placed the html code below, and a php file, test.php, whose contents are also given below. When I click the button I get no error messages and, alas, no indication that the php program has run. Any suggestions ?
I should also add that, using the: form action = "http://localhost/test.php" construct, the test.php does actually execute.
<!DOCTYPE html>
<html>
<head>
<script>
var xmlhttp;
function loadXMLDoc() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = "xxx";
} ;
}
xmlhttp.open("GET", "http://localhost/test.php", true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Using the XMLHttpRequest object</h2>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
<p id="demo"></p>
</body>
The test.php module is just:
<?php
echo "Hello there"
?>
The JavaScript below was adapted from W3Schools. Basically, I just added the URL path to my Servlet in the JS code below.
The Servlet on the server simply returns one of two strings:
(1) GET: Hello from Ajax Server! (**GET**)
(2) POST:Hello from Ajax Server! (**POST**)
The code for the doGet() and doPost() Servlet methods is to just create a PrintWriter from the Response and write a string to it.
The JavaScript below does nothing when I run it by clicking the button. I've omitted the URL to the actual server in the JS code below since that's the customer's site.
Any suggestions would be most welcome.
Thanks,
<!DOCTYPE html>
<html>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xmlhttp.responseText;
};
xhttp.open("GET", "<path_to_server>:8080/AjaxSvr/ajax", true);
xhttp.send();
}
</script>
</body>
</html>
I am trying to implement Ajax calling and i came across the follwing code:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Let AJAX change this text.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "www.google.com", true);
xhttp.send();
}
</script>
</body>
</html>
I am tring to access the URl but ended up in error saying "XHR cannot load".
I know it is something related with CORS. I went through several pages but i am finding it difficult to understand the issue. can somebody please explain and resolve this issue?? Will be helpul
Google dont allow cross domain access to their search engine. Your method seems ok, its just the url you are trying to access doesn't allow your domain.
Try it with a file hosted on your local machine
Hello I have encountered a problem while coding in Javascript and PHP (Ajax non jquery). I am trying to upload a file over Ajax, and handle it in PHP.
This is my code:
index.html
<html>
<head>
<title>PHP AJAX Upload</title>
<script type="text/javascript">
function upload() {
// 1. Create XHR instance - Start
var dat= "bla";
document.getElementById("div2").innerHTML = "working";
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
var rad = document.getElementById('fajl');
var filee = rad.files[0];
var formData = new FormData();
formData.append('rad',filee)
formData.append('var',dat)
xhr.open('POST', 'upload.php');
xhr.send(formData);
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status == 200) {
document.getElementById("div2").innerHTML = xhr.responseText;
//alert(xhr.readyState);
//alert(xhr.status);
}
}
}
</script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<label>Upload File:</label><br/>
<input name="rad" id="fajl" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" onclick="upload()" />
<div id="div2">
</div>
</form>
</body>
</html>
upload.php
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['rad']['tmp_name'])) {
$sourcePath = $_FILES['rad']['tmp_name'];
$targetPath = "images/".$_FILES['rad']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
echo ("uspjeh<br>");
}}
}
$podatak=$_POST['var'];
echo "$podatak"
?>
Problem is that I dont see PHP script response in my div2 element. Ajax behaves wierd and it puzzles me. I have put JavaScript alert command under xhr.readyState condition (now commented). When I do that then I see the output, but when I close alert dialog, the browser automaticly reloads page and makes the URL like i'm using GET method (i'm using POST) and then server output dissapears. (rad in ?rad=... is the name of my input element)
When I'm not using alert command then I don't see output at all, because page redirects really fast. What am I misiing?
It's because you are using a submit button and that's submitting the form. By default form methods are GET requests. Change to just a button instead:
<input type="button" value="Submit" class="btnSubmit" onclick="upload()" />
The default form action (submitting) is being carried out.
To stop this add return false to your click handler:
onclick="upload(); return false;"