Issue
I have a simple HTML form
<form action="#" method="get" id="thisForm">
<button type="submit"> GetJSON </button>
</form>
This is my javascript at the end portion of my body tag
<script src="https://unpkg.com/axios/dist/axios.min.js">
let form = document.getElementById("thisForm");
form.addEventListener('submit', servletAccess())
function servletAccess(e){
e.preventDefault();
console.log("im here")
axios.get('http://localhost:8080/Project1/MyServlet')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
console.log(response);
});
}
</script>
and this is my java servlet returning JSON
JSONArray json = new JSONArray();
JSONObject user = new JSONObject();
user.put("name", "rous");
user.put("age", 26);
user.put("lname", "e");
JSONObject user2 = new JSONObject();
user.put("name", "rene");
user.put("age", 28);
user.put("lname", "solomon");
json.put(user);
json.put(user2);
response.setContentType("application/json");
response.getWriter().write(json.toString());
When directly going to my endpoint by URL, i get the RAW data
[{"lname":"solomon","name":"rene","age":28},{}]
so i know my endpoint works.
How come i couldnt even console.log the response? my dummy console.log("im here") is not even running?
This might be very simple but im stuck with it.
Solution
Your script tag specified 'src' and also inline javascript, when you write it like this your inline js will be ignored, so you have to separate those script tags:
<script src='path/to/axios/'></script>
<script>
// register your form handler
</script>
Also this line:
form.addEventListener('submit', servletAccess())
You registering actual function call as event listener, instead it should be function itself, like this:
// notice no () at the end of function name
form.addEventListener('submit', servletAccess)
Answered By - Monsieur Merso
Answer Checked By - Willingham (JavaFixing Volunteer)