I am trying to post the value of the textbox and have that same value posted on the page in the “You said…” section.
My TypeScript/JavaScript is:
declare var document;
declare var xmlhttp;
window.onload = () => {
start();
};
function sayHello(msg: any) {
// Post to server.
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// All right - data is stored in xhr.responseText
alert("done" + " " + xmlhttp.responseText);
}
else {
// Server responded with a status code.
alert("error");
}
}
}
xmlhttp.open("POST", "Default.cshtml");
xmlhttp.send("someValue=" + msg);
return msg;
}
function start() {
// Add event Listeners for user interaction
var element = document.getElementById("link");
element.addEventListener("click", function () {
var tb = (<HTMLInputElement>document.getElementById("tbox"));
var element = document.getElementById("response")
.innerText = sayHello(tb.value);
}, false);
// Setup XMLHttpRequests (AJAX)
if (XMLHttpRequest) {
// Somewhat cross-browser
xmlhttp = new XMLHttpRequest();
}
else {
// Legacy IE
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
And the HTML is (this page is Default.cshtml):
@{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "Home Page";
var msg = Request["someValue"];
}
<h1>TypeScript HTML App</h1>
<div id="content">
<a href="javascript:;" id="link">Say Hello</a>:
<br />
<input type="text" value="dfgdfgdfg" id="tbox" />
<br />
<p id="response">awaiting a response.</p>
<br />
<p>You said:<br />
@msg</p>
</div>
And I’ve included all references properly:
<script src="~/App.js"></script>
The response code I get back is 200.
Am I doing something wrong here? I’ve followed many tutorials, docs and so forth, and I just don’t see what I’m doing wrong. It looks practically identical.
When you are processing an XMLHttpRequest as a POST, you need to add a couple of extra headers – add them before you call
send, like this:UPDATE – My Full Example
Default.cshtml
App.ts