6

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 :)

Natan Streppel
  • 5,759
  • 6
  • 35
  • 43
user2269361
  • 61
  • 1
  • 1
  • 2
  • Have a look over : [link](http://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax/4113258#4113258) – Ioan Apr 11 '13 at 08:27
  • 1
    Where is the Servlet? Java by itself does not provide HTTP connectivity, you must use a server/framework (Tomcat, Jetty, JBoss). All of them use the Servlet specification, your bussiness class must implement Servlet and be correctly declared in the server. – SJuan76 Apr 11 '13 at 08:29
  • Or, instead of using Servlets, use SOAP (who manages the servlets for you). The first approach should be easier for a newcomer. – SJuan76 Apr 11 '13 at 08:29
  • 1
    A method can be invoked via AJAX (JSON), if you use a RESTFul API like Spring or Struts. Otherwise, you have to send a request to a URL that responds with XML. – Lion Apr 11 '13 at 08:34

2 Answers2

10

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");

Natan Streppel
  • 5,759
  • 6
  • 35
  • 43
Hardik Mishra
  • 14,779
  • 9
  • 61
  • 96
  • @Baadshah: Thank You.. :). Can you please tell what's that ? So, I can edit. – Hardik Mishra Apr 11 '13 at 10:02
  • :) I do not think you don't know may be you forgot.In order to use the java class file,we have to import that in jsp,right? – Suresh Atta Apr 11 '13 at 10:07
  • @Baadshah: As per OP's example I wrote `mail.Main` where `mail` is the package name. :) – Hardik Mishra Apr 11 '13 at 10:35
  • thankyou. i just needed one thing more that how should i pass my variable data in ajax to my jsp file and hence to java method execute? – user2269361 Apr 11 '13 at 11:20
  • How we access `uName` in servlet, if `uName` passing in javascript is array object? That is `var uName = [{id: 1, value: 'one'}, {id: 2, value: 'two'}];`. How we can access object variables too in servlet? – Justin John Jan 12 '14 at 08:23
3

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.

Matsemann
  • 21,083
  • 19
  • 56
  • 89