开发者

jQuery returns undefined with POST call

开发者 https://www.devze.com 2023-02-14 19:37 出处:网络
I\'m sure this is something r开发者_开发知识库eally easy, but I\'m such a noob when I get stuck on these things... It\'s been over 2 hours, I hate when this happens :(

I'm sure this is something r开发者_开发知识库eally easy, but I'm such a noob when I get stuck on these things... It's been over 2 hours, I hate when this happens :(

Why is this returning undefined?

function userExists(user) {
$.post("misc/user_exists.php",  {user: user},
        function(result) {
            return '' + result + '';
        });
});

The php file is returning the user name perfectly fine as I'm seeing it in the responses from firebug. But then this function is useless, when I do an alert after calling it, it's always undefined, whether I return a string, a boolean, etc.

Thank you!


The $.post request is asynchronous, so when you run return '' + result + ''; it's not actually returning data to anywhere. Instead, trigger a different event from inside the AJAX success function.


You need to add the correct dataType parameter for the jQuery post command. Reference: http://api.jquery.com/jQuery.post/


the problem is that the return will only affect the ajax.sucess callback from the post method. Try this:

function userExists(user, callback) //because this can be async, you need a callback...
{
    $.post("misc/user_exists.php",  {user: user},
    function(result) 
    {
        if(callback)
            callback(result)
        return '' + result + '';
    });
};
userExists('someUser', function(result)
{
     alert('' + result + '')
});

or, you can make sure that the call is not async:

function userExists(user) //because this can be async, you need a callback...
{
    var res;
    $.post("misc/user_exists.php",  {user: user},
    function(result) 
    {
        res = result;
    });
    return res;
};
$.ajax({async:false}); 
alert('' + userExists('someUser'+ '');    


You can do like this

function userExists(user) {
    var username = '';
$.post("misc/user_exists.php",  {user: user},
        function(result) {

            username = result ;
        });
   return username;
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号