Sunday, July 26, 2009

[jQuery] Fetching data from callback with $.ajax

Hello all,

I've recently started with jQuery because I wanted to use it for posting details from an login form to a PHP script which should return whether the user is authenticated or not.

For this I use $.ajax, because of it's flexibility and I prefer to use it in this implementation. Reading (jQuery docs and examples) and searching a lot did not solve me on one issue: fetching the data in the callback to the global scope. This one is driving me crazy.

Here is the code:
<script type="text/javascript">
    $(document).ready(function(){       
        var form = $('#form');
        form.submit(function(){ // Only execute this function on submit
            if(isAuthenticated($('#username').val(), $('#password').val())) {
                return true; // I only want the form to be submitted when the credentials are valid (found to be valid by the PHP script)
            } else {
                return false;
            }
        });

        function isAuthenticated(username, password) { // This function call the PHP script to ask whether the credentials are valid or not.
            $.ajax({
                type: "POST",
                url: "json.php?module=login&action=authenticate",
                data: "username=" + username + "&password=" + password,
                success: function(msg) {
                    alert(msg); // This returns 'authenticated' in plain text (at the moment) from the PHP script. Functions fine or course, but I want to use it outside this function. How??
                }
            });

           And here is why I want this to work:
            if(msg == "authenticated") { // This function should be able to read the var 'msg' from the callback in the function above. How?
                alert("Outside: " + msg); // At this point, msg is of course undefined.
                return true;
            }
        }
    });
    </script>

So the only question actually is, how can I let the function that should check the message of the response know that 'msg' has been set?

I hope this makes it clear what I mean ;)


Thanks,
Sander

No comments: