Invoke the Java function via AJAX upon button press

In the file blank.jsp, there is a button as follows:

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

After clicking this button, I want to execute the Java method callprocedure() using AJAX.

function payment()
    {
        alert('Payment done successfully...');
        ........
        // Use AJAX to call the Java method "callprocedure()"
        ........
    }

I am inexperienced with AJAX. Can someone guide me on how to call a Java method using AJAX? Your help is much appreciated. Thank you in advance.

Answer №1

Here is a recommended approach to utilize:

 $.ajax({
            url: '/your-endpoint',
            success: function(data){
            // Executed when the server responds successfully  
            }, error: function(){
               // Executes in case of an error
            }
        });

Answer №2

It appears that your transaction is being handled by a servlet.

All that's required is:

function processTransaction(){
    $.ajax({
        type: "POST",
        url: "yourServletURL",
        success: function(data){
            alert("Transaction successful");
        },
        error: function (data){
            alert("Sorry, transaction failed");
        }
    });
}

Answer №3

  1. remove the onclick attribute from the submit button
  2. add an onsubmit event handler to the form
  3. prevent the form from being submitted

I highly recommend using jQuery for this task, especially if you are working with Ajax requests.

If your servlet function is not within the form tag, replace this.action with the name of your servlet.

$(function() {
  $("#formID").on("submit",function(e) { // pass the event
    e.preventDefault(); // stop submission
    $.post(this.action,$(this).serialize(),function(data) {
      $("#resultID").html(data); // display result in element with id="resultID"
      // If the servlet does not return a response, you can display a message
      // $("#resultID").html("Payment successful");
    });
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Finding the main page URL using PHP within a JavaScript include: A comprehensive guide

I am facing an issue where I have a page with a header include that needs the phone number to change only if the filename of the current page contains a specific word. Typically, for a change outside of an include, the following code would suffice. <? ...

Troubleshooting JavaScript in Internet Explorer 9

Currently, I am encountering an issue while attempting to debug JavaScript .js files in my Solution using Visual Studio 2010 and IE 9. Despite placing breakpoints in the files, I am unable to debug successfully. I have attempted various troubleshooting ste ...

Developing a class with array in Java

I'm looking to develop a class called ExchangeRates that can handle exchange rates for different currencies. Each currency will be represented by a String (e.g. "USD") and a corresponding number (e.g. 5.49). ExchangeRates should have methods to both s ...

Steps for utilizing Bazel to compile TypeScript

Calling all Bazel (Blaze) experts: I'm curious about the best method for integrating Bazel as a build system for cutting-edge web applications built in Typescript. Is there a preferred setup or perhaps a template that demonstrates this integration? T ...

The error message "Unexpected TypeError: useSearchParams either does not exist as a function or is not iterable in its return value

I'm currently facing a problem with my code, which results in the error message: "Uncaught Error: NextRouter was not mounted" appearing in the console. After some investigation, I discovered that with Next.js version 13 onwards, we should ...

Incorrect output when converting JSON to DataTable for Google Visualization

I am attempting to generate a chart using Google Visualization from a CSV file. After parsing the CSV file with PHP, I have extracted the required data in Json format. Specifically, Column 1 contains dates formatted as "dd/mm/yyyy" and Column 2 contains pr ...

Creating dynamic content with Express.js: Using variables in EJS within the request handler

I am looking for a way to include additional variables to be utilized by EJS during the rendering of a view for every request, similar to adding them in the render function: res.render('view', {data: {my: 'object'}}); I have implement ...

What steps should I take to ensure that my website can recall the most recent interaction conducted by the user?

Our website features a search form that allows users to look for items on the page. In addition, there is a separate form with checkboxes that enables users to narrow down their searches in hopes of reducing the number of results returned. For example, i ...

What is the best approach for incorporating multiple conditions in a React component?

I currently have a button labeled Description. When this button is clicked, the description is displayed. Now, I am looking to include a Read more/less option for the description. Unfortunately, using the below code, I am unable to see the button labeled ...

Finding the actual path in any scenario using JavaScript ($.ajax)

Here is the structure of my project: Sil -> css -> js -> clients -> index.php -> response.php index.php I am facing an issue related to the folder 'clients'. My website URL can have different va ...

The "Accept cookies" button is unresponsive to Webdriver's click command, resulting in an "ElementNotInteractable" Exception being thrown

Currently, I am utilizing Cucumber 4.2 and Selenium 3 on Firefox version 64. I'm encountering issues trying to interact with the "Accept cookies" button using Selenium. Despite following the solution provided by DebanjanB for this error, no success h ...

What is the best way to structure a layout? (Using JFrame, JPanel, etc.)

https://i.sstatic.net/wtxDr.png As someone who is just starting out with Java Swing and Java in general, I have a basic understanding of Scanner and the fundamentals. However, when it comes to laying out or positioning elements, I am struggling. The image ...

How can I clear my object so that new Dates() can be added to my calendar?

I am working on updating my program to seamlessly replace old JSON data from a holidays API with new data as soon as it is received. Initially, I attempted to declare the array as empty at the start, but this approach did not yield the desired results. Si ...

Enabling and disabling multiple input fields based on the status of a checkbox in order to manage dynamic inputs

I need help with a situation involving dynamic input fields and checkboxes. My goal is to disable the input field if the checkbox with the corresponding ID is checked. Here is the PHP code snippet: <table class="table table-striped"> <thead& ...

Executing functions during the page loading process

I'm currently in the process of integrating a new payment method into a checkout page that does not have built-in support for it. The button on the page that redirects to an external payment portal requires specific parameters to be passed. I've ...

Would someone be able to clarify the purpose of this await useState React code?

Recently, I came across some React code that directly modifies the state, which goes against what I was taught. However, when I attempted to update it properly, the functionality broke. Clearly, an issue needs to be fixed, but before diving in, I'd li ...

Manipulating an element in the JSON data is causing alterations to the preceding elements

I am facing a challenge with two JSON arrays. $scope.arr1 = [ { "id": 1, "first_name": "Philip", "last_name": "Kim", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e6e7577732e5e737b7a777f78776c7b307d717 ...

Send user a notification upon detecting changes in the database - using JavaScript and AJAX!

Hey there! I'm diving into the world of JavaScript and AJAX for the first time, and I could really use some guidance on a particular issue. I'm looking to implement a feature where the user is notified whenever there is a change in a value of a ...

Encountering a NoSuchElementException error when attempting to use a Datepicker with jQuery

Attempting to click on the input box with a script that should open the URL https://jqueryui.com/datepicker/. The ID locator is available but still getting a "No element found" error. I've also tried using Thread.sleep. When running the script, an ex ...

Guide on transferring an array with a specific key to a function parameter (Dealing with multidimensional arrays)

While this question may seem a bit random, it actually does make sense - at least to me. Let's consider a multi-dimensional array named temporaryFrequency. I want to create a function that takes one argument - frequencyArray[number]. Let's have a ...