Error: Ajax is not a function

AJAX( Asynchronous JavaScript And XML) is a set of web development techniques that uses many web technologies on the client-side to create asynchronous web applications. With Ajax, web applications can asynchronously send and retrieve data from a server without interfering with the existing page’s display or behavior.

AJAX is not a programming language. It requires a built-in browser with the XMLHttpRequest object that requests data from the server, and it uses JavaScript and HTML DOM to display data.

Problem

Let’a create a simple AJAX request that returns some data from a MySQL database:

function AJAXrequest(url, postedData, callback) {
    $.ajax() ({
        type: 'POST',
        url: url,
        data: postedData,
        dataType: 'json',
        success: callback
    });
}

You call the AJAX request,

AJAXrequest('newajax.php', Data, function(data) {
});

but you get the following error on your console:

TypeError: $.ajax(...) is not a function.

Solution

The solution is pretty simple. Many programmers make the mistake of using the jquery cdn-script link that comes with jquery. By default, this is a slim version of jquery, (slim.jquery.js), not the full jquery version. This slim version lacks some key modules, especially the ajax function. Therefore, the slim version does not recognize the ajax function.

To use the ajax function, use:

<script src="https://code.jquery.com/jquery-3.1.1.min.js">

Do NOT use:

<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved