javascript - $.ajax will not work within a function -
i having trouble function using jquery's ajax. function checks api see if variable called "success" true. if is, want function return true. if success false, want return false.
here code:
function loggedin() { $.ajax({ type: "get", url: "/api/auth", success: function (a) { if (a.success == "true") { return true; } else { return false; } } }); }
this code in document (myjs.js, etc), , called html file after jquery , before function called. have script tag in html function called. here is:
<script type="text/javascript"> $(function() { if (loggedin() == true) { $('#send-to-user-btn').css('display', 'block'); $('#sign-in-button-btn').css('display', 'none'); $('#login-bar-my').css('display', 'none'); } }); </script>
i put console.log(loggedin());
in script tags, comes undefined.
any appreciated.
since ajax asynchronous in nature, cannot check value returned function. not guaranteed receive response api endpoint when call ajax function @ runtime.
instead, want check value when promise, returned asynchronous request, has been resolved. here can do:
- in
loggedin()
function, return$.ajax()
object instead. jqxhr object can add methods.done()
(fired when successful),.fail()
(fired when error has been encountered), or
.always()` (which run upon completion). - since want listen success,
loggedin.done()
. callback in within can implement additional logic check if logged in attempt successful (i.e. checking ofsuccess
key true).
using jqxhr.success
callback in $.ajax
discouraged now: officially deprecated in 1.8 , removed in 3.0 (and 1 of reasons why many plugins/sites break when upgrade jquery 3).
here example:
$(function() { // return promise var loggedin = function () { return $.ajax({ type: "get", url: "/api/auth" }); }; loggedin.done(function(response) { if (response.success) { // if loggedin returns success $('#send-to-user-btn').css('display', 'block'); $('#sign-in-button-btn').css('display', 'none'); $('#login-bar-my').css('display', 'none'); } else { // otherwise... } }); });
wiki
Comments
Post a Comment