I am creating a jsp application in Netbeans Ide. I am having problems in calling a java class method in ajax.Is it possible to do so
My java class is something like this:
public class Hello
{
public String execute(String s)
{
return "success";
}
}
I am not able to figure out how to call the execute method using ajax : My current ajax code is:
var val="test string";
$.ajax({
type: "GET",
url: "http://localhost:8084/Shade/src/java/mail/Main.execute",
data: val,
async: true,
cache: false,
success: function (msg) {
alert("hi");
$(".col-1").html(msg);
});
Thanx in advance :)
AJAX
is an acronym for Asynchronous JavaScript And XML
. It provides an ability to communicate with the server asynchronously.
To explain that in simple terms, you can send a request to server and continue user interaction with the user. You need not wait for response from the server. Once the response arrives, a designated area in UI will update itself and reflect the response information. Whole page need not be reloaded.
So, you can not access Java Class directly as url
to make your Ajax request. It should any mapped url like JSP
, Servlets
, PHP
etc.
Create a JSP (e.g. hello.jsp
)
<%
String strResponse;
mail.Main objMain = new mail.Main();
strResponse = objMain.execute();
%>
<%=strResponse %>
In Ajax request
url: "hello.jsp",
EDIT: Added Example:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
function getData() {
var dataToBeSent = {
uName : $("#userName").val() , //
passwd: $("#password").val()
}; // you can change parameter name
$.ajax({
url : 'getDataServlet', // Your Servlet mapping or JSP(not suggested)
data :dataToBeSent,
type : 'POST',
dataType : 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
success : function(response) {
$('#outputDiv').html(response); // create an empty div in your page with some id
},
error : function(request, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
});
In Servlet/JSP access your parameters request.getParameter("uName");
You cannot call the method directly. You should map an URL to the method you want to call. This can be done in a servlet. If you're already serving pages through your Java code, you just add a new method to serve a page with the content you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With