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.

Suniel
  • 1,449
  • 8
  • 27
  • 39

3 Answers3

2

try to use this method..

 $.ajax({
            url: '/servlet/yourservlet',
            success: function(result){
            // when successfully return from your java  
            }, error: function(){
               // when got error
            }
        });
Raymond
  • 572
  • 4
  • 13
  • 28
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");
        }
    });
}
me_digvijay
  • 5,374
  • 9
  • 46
  • 83
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");
    });
  });
});
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 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 – Raymond May 20 '13 at 04:48
  • Mine is much simpler (shortcut) and is not using the deprecated success/error – mplungjan May 20 '13 at 04:51