ArticleZip > 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

Imagine you are working on a web project and want to send an AJAX request when a user clicks a button on a form that has two buttons. This scenario is quite common, especially in web development where you need to update parts of a webpage without refreshing the whole thing. In this article, we will explore how to achieve this by using JavaScript to send an AJAX request when a specific button is clicked.

First, let's set up the HTML form with two buttons. You can create a simple form with two buttons like this:

Html

<button id="button1">Button 1</button>
  <button id="button2">Button 2</button>

In the above code snippet, we have a basic form with two buttons, each having a unique ID for identification.

Next, we will write the JavaScript code to handle the AJAX request when one of the buttons is clicked. Let's use the Fetch API to send an AJAX request to a server endpoint. Here's an example of how you can do this:

Javascript

document.getElementById('button1').addEventListener('click', function() {
  fetch('your_server_endpoint_url')
    .then(response =&gt; response.json())
    .then(data =&gt; {
      // Handle the response data here
      console.log(data);
    })
    .catch(error =&gt; {
      console.error('Error:', error);
    });
});

document.getElementById('button2').addEventListener('click', function() {
  // AJAX request for button 2
});

In the JavaScript code above, we attached click event listeners to both buttons. When `button1` is clicked, an AJAX request is sent using the Fetch API to a specified server endpoint. Replace `'your_server_endpoint_url'` with the actual URL you want to send the AJAX request to. The response data from the server can be accessed in the callback functions of the `then` method.

For `button2`, you can add a similar AJAX request logic or any other functionality you require.

It's essential to handle errors in your AJAX request to provide a better user experience. The `catch` method in the Fetch API is used for error handling.

Remember to include proper error handling, validation, and security measures in your actual implementation to ensure the reliability and security of your application.

By following these steps, you can send an AJAX request when a button is clicked in a form with two buttons. Experiment with different functionalities and customize the code to fit your specific use case and project requirements.

Happy coding and best of luck with your web development endeavors!