excavator excavator - 1 month ago 22
Javascript Question

JS loadResponse doesnt work

I am building a basic calculator using JavaScript.

<script>
function loadResponse(x){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("resultDiv").innerHTML = xmlhttp.responseText;
}
}
var uri = "http://localhost:8080/REST_service/rest/calculator/";
switch(x){
case 1:
uri += "add/";
break;

case 2:
uri += "subtract/";
break;

case 3:
uri += "multiply/";
break;

case 4:
uri += "divide/";
break;
default:
break;
}

uri += document.getElementsByName("num1").value + "/" +
document.getElementsByName("num2");
console.log(uri);
xmlhttp.open("POST", uri, true);
xmlhttp.send();
}
</script>
<body>
Number 1: <input type="text" name="num1" />
Number 2: <input type="text" name="num2" />
<input type="button" onclick="loadResponse(1)" value="ADD" />
<input type="button" onclick="loadResponse(2)" value="SUBTRACT" />
<input type="button" onclick="loadResponse(3)" value="MULTIPLY" />
<input type="button" onclick="loadResponse(4)" value="DIVIDE" />

<div id="resultDiv"></div>
</body>


But the console.log doesnt work, so the function is not getting called.

What am I doing wrong? How can I improve this code- calling loadResponse in a better way and also sending the values across to server side?

Thanks

Answer

This line is wrong:

    uri += document.getElementsByName("num1").value + "/" +
                document.getElementsByName("num2");

getElementsByName() returns a NodeList, so you need to index it to access the value. And you didn't use .value for the second field. It should be:

    uri += document.getElementsByName("num1")[0].value + "/" +
                document.getElementsByName("num2")[0].value;
Comments