Suniel
Suniel

Reputation: 1499

call the java method using ajax on button click

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.

Upvotes: 1

Views: 17266

Answers (3)

mplungjan
mplungjan

Reputation: 178403

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

Upvotes: 1

me_digvijay
me_digvijay

Reputation: 5502

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

Upvotes: 2

Raymond
Raymond

Reputation: 572

try to use this method..

 $.ajax({
            url: '/servlet/yourservlet',
            success: function(result){
            // when successfully return from your java  
            }, error: function(){
               // when got error
            }
        });

Upvotes: 2

Related Questions