0
I'm using XMLHttpRequest POST to send data to a jsp. But the jsp is not invoked. Here is my code.

The JS method is called on a button click

<form action="">
<div><input type="button" value="POST DATA"
    onclick=test();
/></div></form>

JS method to do a http POST -

<script>
function test() {
        var xmlHttpRequest = new ActiveXObject('Msxml2.XMLHTTP');
        xmlHttpRequest.open("post",
                "http://localhost:4502/content/myTest.html", true);
        xmlHttpRequest.setRequestHeader("Content-Type",
                "application/x-www-form-urlencoded");
        xmlHttpRequest.onreadystatechange = function() {
            getResult(xmlHttpRequest)
        };
        try {
            xmlHttpRequest.send("username=john");
        } catch (e) {
            alert("error" + e);
        }
    }
    function getResult(xmlHttpRequest) {
        if (xmlHttpRequest.readyState == 4) {
            if (xmlHttpRequest.status == 200) {
                alert("ok");
            } else {
                alert("error" + xmlHttpRequest.status);
            }
        }
    }
</script>

myTest.jsp to write POST request to a text file -

  <%
    FileOutputStream fos = new FileOutputStream("D:/test.txt");
    PrintWriter pw = new PrintWriter(fos);
    pw.println(request.getParameter("username"));
    %>

myTest.jsp is not getting invoked but i get the OK alert. If i try http get instead of post and append parameters to the uri, it works. I'm using IE8.

Pls help.

Shawn
  • 8,374
  • 5
  • 37
  • 60
arvind
  • 17
  • 7

1 Answers1

0

Have you tried using jQuery for making your post?

You would need to include the jQuery library in your page before using it.

Using jQuery will also make your code cross-browser compatible, and the examples on that link are easier to follow. There are other jQuery options if you want more control over the request as well. I highly recommend it--for tasks like this and many others, it will make your life simpler and your coding more enjoyable!

Shawn
  • 8,374
  • 5
  • 37
  • 60
  • Yea, I was able to create a fully functional jquery ajax xmlhttprequest, but their api doesn't have their Allow-Control-Access-Origin setup on their server for 'security reasons'. – Joseph Casey Jun 12 '14 at 18:14
  • If the service you are hitting supports JSONP that will solve this issue. If it doesn't support it, perhaps it should. See also http://stackoverflow.com/questions/20518653/jsonp-cross-origin-error-no-access-control-allow-origin-header-is-present – Shawn Jun 12 '14 at 19:19