Last updated: Mar 2, 2024
Reading time·2 min
The "$.ajax is not a function" error occurs when loading the slim version of
jQuery and trying to use the ajax
function.
The ajax
function is excluded from the slim jQuery version. To solve the
error load the regular jQuery version on your page.
Instead of loading the slim
version, load the minified
version of jQuery.
You can find a link to the CDN by going to the
jQuery site.
Make sure to add a script that points to the minified
version and not the
slim
one.
Here is a working example of using the ajax
function.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <!-- ✅ load jQuery ✅ --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous" ></script> </head> <body> <button id="btn">Make request</button> <script src="index.js"></script> </body> </html>
Here's the code for the index.js
file.
$(document).ready(function () { $('#btn').click(function () { $.ajax({ url: 'https://randomuser.me/api/', dataType: 'json', success: function (data) { console.log(data); }, }); }); });
We added an event listener to the button. Every time the button gets clicked it makes a GET request to an API and logs the output to the console
If you load the page and click on the button, you will see the API response printed in your console.
If you still get the error you might be loading the jQuery library twice.
Loading the library twice re-runs the initialization process and causes the error.
You can check if you're loading the scripts correctly by opening your Developer
tools by pressing F12
and clicking on the Console
tab.
If you see any 404
errors related to loading the jQuery scripts, then the path
to the file is incorrect.
To solve the "$.ajax is not a function" error, add the regular jQuery script
to the page and remove the slim
version.
The slim
jQuery version doesn't include the ajax
function.