Wait until ajax done before returning the function : <p>I use this code to get a message from the server and print it to the frontend:</p>

<pre><code>var message = getMessageFromServer();
$('.result').html(message);

function getMessageFromServer() {
    var result = null;

    $.ajax({
        url: 'index.php',
        type: 'GET',
        success: function (msg) {
            result = msg;
        }
    });

    return result;
}
</code></pre>

<p>It obviously isn't working because as how javascript works, the line <code>return result</code> is running before the ajax done, therefore my function <code>getMessageFromServer</code> always return null.</p>

<p>I have searched all day about this problem and got many answers such as setting async to false, using when done, callback, re-structuring the code to be more ajax-friendly, etc. However, I'm using a framework that won't let me freely re-structuring my code, so I need to make the question myself: <strong>How do I print the message to the frontend with below conditions</strong>:</p>

<ul>
<li><p>The 2 first lines must not be changed, I need to return the result to <code>message</code>, so it can be print to the frontend.</p></li>
<li><p>Not using the <code>async: false</code> because it's bad for user experience.</p></li>
<li><p>We can create more method, as long as it is used within the function <code>getMessageFromServer</code></p></li>
</ul>

<p>P/s: If you're wondering, the framework I'm using is Magento and I'm trying to add a custom validation rule with AJAX, but I the main problem is javascript so I didn't put it into the tags.</p>
