How can I send an Ajax Request on button click from a form with 2 buttons?

How can I send an Ajax Request on button click from a form with 2 buttons?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Decoupling Logic in Multi-Button Forms

Your current implementation works, but it relies on a repetitive pattern that makes maintenance difficult. You are essentially copying and pasting the same AJAX logic twice, differing only by the button's ID and value. While this might seem manageable for two buttons, it becomes fragile as soon as you add a third, fourth, or fifth option. The goal is to refactor this into a single handler that determines which action occurred dynamically.

The most robust approach involves delegating the event listener to a parent element rather than attaching individual listeners to each button. This technique, known as event delegation, ensures that even dynamically added buttons in the future will trigger the correct logic without needing to re-bind events.

Here is how you can consolidate your code into one efficient function:

$(document).ready(function() {
  // Delegate the click event to the form element
  // This handles clicks on current and future buttons inside the form
  $("#form_id").on("click", "button", function(e) {
    e.preventDefault();

    // Determine which button was clicked by checking the 'name' attribute
    const actionName = $(this).attr('name');
    
    // Extract the specific value from the button
    const idValue = $(this).val();
    
    // Retrieve the hidden token once, as it's common to both requests
    const accessToken = $("#access_token").val();

    $.ajax({
      type: "POST",
      url: "/pages/test/",
      data: {
        but1: actionName === 'but1' ? idValue : null, // Only send relevant data
        but2: actionName === 'but2' ? idValue : null,
        access_token: accessToken
      },
      success: function(result) {
        alert('ok');
      },
      error: function(xhr, status, error) {
        console.error("Request failed:", error);
      }
    });
  });
});

Handling Data Semantics

In your original code, you keyed the data object using id, but in the HTML, the buttons are named but1 and but2. When merging logic, it is crucial to understand how your backend expects the data. In the refactored example above, we explicitly map the button name to a specific property (but1 or but2) in the AJAX payload.

Alternatively, if your backend prefers a unified key like action, you can adjust the logic inside the click handler:

$.ajax({
  type: "POST",
  url: "/pages/test/",
  data: {
    action: $(this).attr('name'), // Sends 'but1' or 'but2'
    value: $(this).val(),
    access_token: accessToken
  },
  // ...
});

This approach makes the server-side logic cleaner, as it can simply check if ($_POST['action'] === 'but1') rather than checking for specific keys.

Security Considerations for Access Tokens

Your form includes a hidden access_token populated from $_SESSION. This is a common pattern for stateful authentication or CSRF protection. When moving to AJAX requests, you must ensure the token is sent in every request. Your current code does this correctly by grabbing the value via jQuery selector inside the event handler.

However, be wary of how you handle the success callback. Using alert() blocks the UI thread and provides a poor user experience. In a production environment, you should update the DOM or fetch new data based on the server's response asynchronously. Additionally, never log sensitive tokens to the console unless you are in a strictly controlled development environment; always treat access_token values as sensitive credentials.

Performance Implications of Event Delegation

By attaching the listener to the form (#form_id) instead of individual buttons, you save memory and processing power. Browsers optimize delegated events efficiently. If you have hundreds of buttons on a page, attaching listeners to each one individually creates significant overhead compared to a single delegation handler. This pattern scales linearly with your application's complexity without degrading performance.

Finally, remember that e.preventDefault() is essential here because your form has a method="post". Without preventing the default action, clicking the button would submit the entire form via a full page reload, potentially overwriting your AJAX response or causing a race condition where the browser navigates before the server responds.

Our network