Open In App

How to Make a Simple jQuery AJAX Call on Link Click?

Last Updated : 12 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To make a simple jQuery AJAX call when a link is clicked, you can use jQuery's .click() method and the $.ajax() function to send a request and handle the response. Here's a basic example to demonstrate how this works:

Example: jQuery AJAX Call on Link Click

HTML Structure:

HTML
<a href="#" id="myLink">Click me to send AJAX request</a>
<div id="response"></div>

<!-- Include jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Output:

Screenshot-2024-11-12-113240
Output

jQuery AJAX Call on Link Click:

JavaScript
$(document).ready(function() {
  $('#myLink').click(function(event) {
    event.preventDefault(); // Prevent the default link behavior

    // Make an AJAX request
    $.ajax({
      url: 'process.php', // Replace with your server-side script URL
      type: 'GET', // or 'POST' depending on your needs
      success: function(response) {
        // Display the response inside the #response div
        $('#response').html('Server Response: ' + response);
      },
      error: function() {
        $('#response').html('An error occurred while processing the request.');
      }
    });
  });
});

Explanation:

  1. $('#myLink').click():
    • Attaches a click event listener to the link with the ID myLink.
  2. event.preventDefault():
    • Prevents the default behavior of the <a> element (which would typically cause a page reload or navigation).
  3. $.ajax():
    • Sends an asynchronous HTTP request.
    • url: Specifies the URL of the server-side script to handle the request (e.g., process.php).
    • type: Specifies the request method ('GET' or 'POST').
    • success: A callback function that handles the response when the request is successful.
    • error: A callback function that handles errors if the request fails.

Key Points:

Replace 'process.php' with the appropriate URL of your server-side script that will process the request.

You can modify the data sent with the request using the data property within the $.ajax() call, like so:

JavaScript
$.ajax({
  url: 'process.php',
  type: 'POST',
  data: { key1: 'value1', key2: 'value2' },
  success: function(response) {
    $('#response').html('Server Response: ' + response);
  }
});

This example demonstrates how to make a simple jQuery AJAX call when a link is clicked, preventing default behavior, sending a request to the server, and displaying the response on the page


Next Article

Similar Reads