This guide shows you how to make a simple AJAX request with jQuery when a user clicks a link. You’ll send a request to the server without reloading the page, and you’ll handle the response in the browser. This is useful for loading content dynamically, submitting forms, or fetching data. You’ll need a basic understanding of HTML, JavaScript, and jQuery, and a web server (or a local development environment) to test the request.
What You’ll Need
- A web page with jQuery included (via CDN or local file).
- A server-side endpoint (like a PHP, Node.js, or Python script) that returns data. For this example, we’ll use a simple text file or a script that returns JSON.
- A text editor and a browser with developer tools (to see the network requests).
Step-by-Step
- Set up your HTML file. Create a basic HTML file and include jQuery. You can use the official CDN:
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> - Create a link that you want to trigger the AJAX call. Give it an ID or a class so you can target it with jQuery. For example:
<a href="#" id="load-data">Load Data</a> - Add a container to display the response. This is where the data from the server will appear. For example:
<div id="result"></div> - Write the jQuery code. Inside a
<script>tag, or in a separate JS file, add a click handler for the link. Use the$.ajax()method to make the request. Here’s a basic example:$(document).ready(function() { $('#load-data').on('click', function(event) { event.preventDefault(); // Prevent the default link behavior $.ajax({ url: 'data.txt', // or your server endpoint method: 'GET', dataType: 'text', success: function(response) { $('#result').text(response); }, error: function(xhr, status, error) { $('#result').text('Error: ' + error); } }); }); }); - Test it. Open the HTML file in a browser (preferably via a local server, like using
python -m http.serveror a tool like Live Server). Click the link and you should see the content ofdata.txtappear in the#resultdiv without a page reload. - Handle JSON data. If your server returns JSON, change
dataTypeto'json'and use the response as an object. For example, if the server returns{"message": "Hello!"}, you can do:success: function(response) { $('#result').text(response.message); } - Send data with the request. If you need to send parameters, use the
dataoption. For a GET request, it appends to the URL; for POST, it sends in the body. Example:$.ajax({ url: 'submit.php', method: 'POST', data: { name: 'John', age: 30 }, // ... }); - Use the shorthand methods. jQuery also provides
$.get()and$.post()for simpler cases. The above GET example could be:$.get('data.txt', function(response) { $('#result').text(response); });
Common Mistakes
- Forgetting to prevent the default link action. If you don’t call
event.preventDefault(), the browser will navigate to thehrefattribute, which usually causes a full page reload. - Not waiting for the DOM to be ready. If you attach the click handler before the DOM is fully loaded, the element may not exist yet. Always wrap your code in
$(document).ready()or use the shorthand$(function() { ... });. - Incorrect URL path. The URL in the AJAX call is relative to the current page. If your page is at
/folder/page.htmland you useurl: 'data.txt', it will look for/folder/data.txt. Use a leading slash for absolute paths, or adjust accordingly. - Ignoring the error callback. If the request fails (404, server error, network issue), the success callback won’t run. Always include an error handler to debug and inform the user.
- Mixing data types. If the server returns JSON but you set
dataType: 'text', the response will be a string, not an object. Make sure the dataType matches what the server actually returns.
Tips
- Use the browser’s developer tools. Open the Network tab to see the request and response, and the Console for any JavaScript errors.
- Cache control. For GET requests, browsers may cache the response. If you need fresh data, you can add
cache: falseto the AJAX options, or append a timestamp to the URL. - Loading indicators. Show a spinner or “Loading…” message while the request is in progress. You can use the
beforeSendandcompletecallbacks. - Use
.done()and.fail(). These promise-based methods are more readable thansuccessanderrorcallbacks, especially for chaining. - Validate input on the server. Never trust client-side data. Always validate and sanitize on the server side.
Troubleshooting
- Nothing happens when you click the link. Check the browser console for errors. Common issues: jQuery not loaded (check the CDN link), the element ID is misspelled, or the script runs before the DOM is ready.
- The AJAX request returns a 404 error. The URL is wrong. Check the Network tab to see the exact URL that was requested. Make sure the file exists at that path.
- The response is not displayed. Check the success callback. If the response is JSON, make sure you are accessing the correct property. If the response is HTML, use
.html()instead of.text()to render it. - Cross-origin issues. If you are making a request to a different domain, you may get a CORS error. The server must include the appropriate CORS headers. For local testing, use a local server or disable CORS in the browser (not recommended).
- The request works but the page still reloads. You forgot to call
event.preventDefault(). Add it as the first line in the click handler.
Frequently Asked Questions
Can I use this with any server-side language?
Yes, AJAX is language-agnostic. The server just needs to respond with data, typically in text, HTML, or JSON. You can use PHP, Node.js, Python, Ruby, etc.
What is the difference between GET and POST in AJAX?
GET sends data in the URL (visible, limited length) and is used for fetching data. POST sends data in the request body (more secure, no size limit) and is used for submitting data that changes the server state.
How do I handle errors gracefully?
Use the error callback or the .fail() method. You can show a user-friendly message and log the technical error to the console.
Can I make multiple AJAX calls at once?
Yes, you can use $.when() to run multiple calls and then execute a callback when all are done. Or simply call $.ajax() multiple times; they run asynchronously.
Is it better to use $.ajax() or $.get()/$.post()?
Use $.get() and $.post() for simple requests. Use $.ajax() when you need more control, like setting headers, timeouts, or handling different data types.
How do I send form data with AJAX?
You can serialize the form using $('#myForm').serialize() and pass it as the data option. For files, use FormData and set processData: false and contentType: false.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Delete Picture Kik? How to Remove Photos
- Data Breaches That Shook the World
- Disable Google Assistant: Turn It Off on Android & Home
- Resin vs FDM Printers for Miniatures: Detail, Durability, Cost
- Are Networked Implants Safe? What If One Fails?
- How to Stop WordPress Comment Spam: A Layered Guide