0

Here is my codes,

function getMods(name){
    var init;
    $.ajax({
    type: "POST",
    url: "init.php",
    data: { 'id': getID(), 'Name': name },
    cache: false,
    success: function(data)
        {
            return data;
        },
        async:false
    });
}
function init(){
    var gm = '<br/>';
    var gm1 = getMods('Name');
        $('#brand').append(gm1);
    var gm2 = getMods('Owner');
    var gm3 = getMods('Admin1');
    var gm4 = getMods('Admin2');
    var gm5 = getMods('Admin3');
    var gm6 = getMods('Admin4');
    $('#online3').append(gm2 + gm + gm3 + gm + gm4 + gm + gm5 + gm + gm6 + gm);
}

The getMods() returned "undefined". When i use this code:

alert(data);

The page alerted the correct values.

Here is the php file init.php:

<?php
include('dbconnect.php');
if(isset($_POST['id']) && isset($_POST['Name'])){
$id = $_POST['id'];
$name = $_POST['Name'];
$init = chatMods($name,$id,$username,$password);
echo $init;
}
?>

And I add the async in the getMods().

John Bobs
  • 489
  • 1
  • 6
  • 12

1 Answers1

0

You should make the distinction between a return value of a function (getMods() in your case) and a callback function (success).

In your code, you call getMods() which in fact doesn't return any value, hence you get undefined.

The success callback happens only after a while, after your function had already returned.

One possible solution for you (though not the greatest because it locks your JS processing) is to use an Ajax call in a synchronous way. A call that only returns when an answer from the server has been received. Use async: false in your $.ajax call, capture your return value and then return it. See this example: https://stackoverflow.com/a/2592780/290343

You should be aware, of course, that your Ajax calls might fail and you need to take that into account. Also, your code might run really slow because it does 6 remote calls to a server.

Community
  • 1
  • 1
Ofer Zelig
  • 17,068
  • 9
  • 59
  • 93