jQuery synchronous Ajax request returns 'undefined' -
this question has answer here:
- how return response asynchronous call? 21 answers
i trying jquery synchronous ajax call return boolean value, when test return value 'undefined'.
jquery code:
function foo() { var username = "hello" if (checkusernameexist(username)) { //do here } } function checkusernameexist(username) { return $.ajax({ type: 'post', url: "check_username.php", data: { username: username}, async: false, }).responetext; }
php code:
<?php //sets connection (among other things) include 'common.php'; //check have username post var if(isset($_post['username'])) { //check if ajax request, exit if not if(!isset($_server['http_x_requested_with']) , strtolower($_server['http_x_requested_with']) != 'xmlhttprequest') { die(); } $un = $_post['username']; //check username in db $results = pg_query($con,"select * users username='{$un}'"); //return total count $username_exist = pg_num_rows($results); //total records if ($username_exist == 1) { echo true; } else { echo false; } } ?>
thanks in advance.
i use success call , works:
function checkusernameexist(username) { var exists; $.ajax({ type: 'post', url: "check_username.php", data: { username: username}, async: false, success: function(response){ exists = response; } }) reutrn exists; }
note:
it's not recommended practice make ajax calls synchronous halt ui on browser. if ajax call takes long complete, user won't able on website until it's done.
Comments
Post a Comment