Simple JavaScript to Servlet POST or GET doesn't work - javascript

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>

Related

Sending a Request To a database(google sheets)

I have created a script within google sheets. It gives a result of a cell from my table in google sheets(kinda database). I want the result send to my html page, and i have tried so far with XMLHttprequest but with no success.
What have i done wrong?
Here is the Script
<script>
function load() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "https://script.google.com/macros/s/AKfycby5RzvUWSEOjerJpouxN72wpsgpsF8IWQo2AvjZUdRPcqskz28/exec", true);
xhttp.send();
}
</script>
<html>
<body>
<h1>Members:</h1>
<button type="button" onclick="load()">Request data</button>
<p id="demo"></p>
</body>
</html>
To read a spreadsheet from google:
download a script called Tabletop and add it to your HTML. (The readme is here)
In Google Docs go up to the File menu and pick Publish to the web. Then click Start publishing. A URL will appear, something like https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE&output=html, that is the URL you will use.
Then call it with this:
<script type="text/javascript">
var public_spreadshseet_url = 'https://docs.google.com/spreadsheet/pub?YOUR_URL_HERE';
// YOUR_URL_HERE sample: hl=en_US&hl=en_US&key=0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE&output=html
// You get this URL from google docs after you publish the spreadsheet
function init()
{
Tabletop.init(
{
key: public_spreadshseet_url,
callback: showInfo,
simpleSheet: true
})
}
// This function gets called to give output
function showInfo(data)
{
alert("Successfully processed!")
console.log(data); <-- Here is the spreadsheet data
}
</script>
<html>
<body>
<h1>Members:</h1>
<button type="button" onclick="init()">Request data</button>
<p id="demo"></p>
</body>
</html>

XMLHttpRequest call backend python cgi script, python script not responding

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.

can't run php in xampp

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"
?>

How to use CORS?

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

What is wrong with this code using ajax?

I'm new to coding and now I'm trying to write a code that gets the text data form a file and replace the present text with the new one. I'm using AJAX to do the task but the problem is first I'm getting the error message and then expected answer The error message is what I have included in the code to display when there is error. Even though i'm getting the desired answer I want to know why the error message is displayed. Here is my code
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<script>
function loadXML() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest;
}
else {
xmlhttp = new ActiveXObject("MICROSOFT.XMLHTTP")
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("p1").innerHTML = xmlhttp.responseText;
}
else {
alert(" there is a error in your code");
}
}
xmlhttp.open("GET","robots.txt", true);
xmlhttp.send(null);
}
</script>
</head>
<body>
<p id="p1">This is Text</p>
<button id="b1" onclick="loadXML()">Click me </button>
</body>
</html>
The problem is your if-block in onreadystatechange. During the request and response, xmlhttp.readyState changes multiple times and onreadystatechange is called every time this happens.
If you do it like this, it may work:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 ) {
if( xmlhttp.status == 200 ) {
document.getElementById("p1").innerHTML = xmlhttp.responseText;
} else {
alert(" there is a error in your code");
}
}
It is simpler, however, to use the other event-methods like onload and onerror, as described here.
1- include 1 jQuery file jquery-1.9.0.js same as jquery-1.9.0.min.js but jquery-1.9.0.min.js is minified file
2- what is the Error message from javaconsole log ?
3- you are using jQuery so why you are working with XMLHttpRequest when jQuery $.get already using best of HttpRequest for all browsers
you can replace your JS code with this
<script type="text/javascript">
$( document ).ready(function() {
$.get('robots.txt',function(data){ $('#p1').html(data) });
});
<script>
Are you using a webserver ? Ajax doesn't work from local file url : 'file://...'
alert(" there is a error in your code");
Actually there is no error in your code. xmlhttp.onreadystatechange is called in different states of the request. Thats why you check for xmlhttp.readyState == 4. Learn more about the different stages here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
So your code is running fine, you just alert an error message, that is not an error at all.

Categories