Issue
I would like to perform a get request from a JSP file and get display the json response.
The link for the get request will look like this :
https://api.fda.gov/drug/label.json?search="testicular cancer"
However I would like to replace the search parameter with an input parameter from an html form
The html form is in the index.html file:
<html>
<body>
<form action="login.jsp" method="post">
<input type="text" name="disease" placeholder="Enter Disease Name"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
In the login.jsp file I wrote the following code, based on a suggestion to use ajax (from the comments):
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
function calling(){
$.ajax({
url : 'https://api.fda.gov/drug/label.json?search="testicular cancer"',
type : 'GET',
dataType : 'json',//
contentType : 'application/json',
complete : function(response) {
console.log(response);
}
});
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type="button" value="Call Servlet" name="Call Servlet" onclick="calling()"/>
</body>
</html>
However I can't see any results when I click the button "Call Servlet". What can I do to correct it?
I am using tomcat in ubuntu 18.04.
Solution
You could remove the onClick from html and add it to jquery on ready like :
$(document).ready(function() {
$('#callServlet').click(function(){
$.ajax({
url : 'https://api.fda.gov/drug/label.json?search="testicular cancer"',
type : 'GET',
dataType : 'json',//
contentType : 'application/json',
success: function(response) {
console.log(response);
}
error: function(response) {
console.log(response);
}
});
});
});
<input type="button" value="Call Servlet" id="callServlet" />
or just use the onClick
trigger in html like you have donw now, just make sure to have success as well as error callbacks for ajax.
If you want the json to be displayed in a div with an id like result
then do like for example :
$('#result').html(JSON.stringify(response));
Add the above code to the success or error callbacks of an ajax to add the response to the html as json string.
Answered By - Ananthapadmanabhan