ajax is asynchronous. That means it finishes some time AFTER the ajax function itself completes. So you can't just simply return a value from your success handler and expect that to be returned from the ajax function.
In fact, returning a value from the success handler does absolutely nothing. The value just goes back into the internals of the ajax infrastructure.
What you need to do is to put your alert inside the success handler. Any code that wants to use the result of the ajax call must be in the success handler or called from the success handler:
$.ajax({
type: "post",
url: "count.jsp",
data: "",
cache: false,
success: function(str) {
// put code here to use the ajax data
// or call a function here and pass it the ajax data
alert(str);
}
});
Further, per the jQuery documentation the return value from the jQuery .ajax()
function is a jqXHR object.
And, the more modern way to use $.ajax()
is to use promises. The jqXHR object it returns is also a promise. The general concept is this:
$.ajax(...).then(result => {
console.log(result);
}).catch(err => {
console.log(err);
})