1

I have a button in blank.jsp (lets say).

<input class="submit_button" type="submit" id="btnPay" name="btnPay" value="Payment" 
style="position: absolute; left: 350px; top: 130px;" onclick="javascript:payment();">

when button is clicked I need to call the java method callprocedure() using ajax.

function payment()
    {
        alert('Payment done successfully...');
        ........
        // ajax method to call java method "callprocedure()"
        ........
    }

I am new to ajax. how can we call the java method using ajax. Please help me soon. Thanks in advance.

1

3 Answers 3

2

try to use this method..

 $.ajax({
            url: '/servlet/yourservlet',
            success: function(result){
            // when successfully return from your java  
            }, error: function(){
               // when got error
            }
        });
Sign up to request clarification or add additional context in comments.

2 Comments

That is quite inelegant and error and success have been replaced by fail and done
@mplungjan, thanks for your advice.. i m still learning ajax.. could you point out more detail? thanks..
2

I suppose your payment is in a servlet.

All you need is this

function payment(){
    $.ajax({
        type: "POST",
        url: "yourServletURL",
        success: function(data){
            alert("Payment successful");
        },
        error: function (data){
            alert("sorry payment failed");
        }
    });
}

Comments

1
  1. remove the inline onclick from the submit
  2. add an onsubmit handler to the form
  3. cancel the submission

I strongly recommend jQuery to do this especially when you have Ajax involved

I assume here the servlet function is in the form tag. If not, exchange this.action with your servlet name

$(function() {
  $("#formID").on("submit",function(e) { // pass the event
    e.preventDefault(); // cancel submission
    $.post(this.action,$(this).serialize(),function(data) {
      $("#resultID").html(data); // show result in something with id="resultID"
      // if the servlet does not produce any response, then you can show message
      // $("#resultID").html("Payment succeeded");
    });
  });
});

2 Comments

i would like to know what's the differences your method and directly call ajax? I'm still learning ajax.. please advise... thanks a lot
Mine is much simpler (shortcut) and is not using the deprecated success/error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.