I'm new to jQuery and using a little old tutorial on node.js
that uses this snippet :
$(function () { var roomId; $.ajax({ type: "GET", url: "/api/rooms" }).success(function (rooms) { roomId = rooms[0].id; getMessages(); $.each(rooms, function (key, room) { var a = '<a href="#" data-room-id="' + room.id + '" class="room list-group-item">' + room.name + '</a>'; $("#rooms").append(a); }); }); [...] });
However I get this error
Uncaught TypeError: $.ajax(...).success is not a function
at }).success(function (rooms) {
I'm wondering what can be wrong here?
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 does not include the ajax function.
What is AJAX success? AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.
The call to ajax should look like:
$.ajax({ type: "GET", url: "/api/rooms", success: function (rooms) { } });
You don't method chain the success function, it is one of the entries in the dictionary argument.
Your code is correct there is no problem with it
but you might be including the new jquery library which doesn't allow .success() method
for newer version of jquery use
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> $.ajax({ type: "GET", url: "/api/rooms", success: function (rooms) { } }); </script>
and if you are using old jquery the .success() method would run without any problem
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> $.ajax({ url: "/api/rooms", method: "GET", data: {'datavar': datavalue} }).success(function (rooms) { console.log("successfully run ajax request..." + rooms); }).done(function () { console.log("I am from done function"); }).fail(function () { console.log("I am from fail function."); }).always(function () { console.log("I am from always function"); }); </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With