-2

I use this code to get a message from the server and print it to the frontend:

var message = getMessageFromServer();
$('.result').html(message);

function getMessageFromServer() {
    var result = null;

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

    return result;
}

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

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: How do I print the message to the frontend with below conditions:

  • The 2 first lines must not be changed, I need to return the result to message, so it can be print to the frontend.

  • Not using the async: false because it's bad for user experience.

  • We can create more method, as long as it is used within the function getMessageFromServer

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.

Mee
  • 223
  • 4
  • 13

1 Answers1

0

It's the nature of JS and asynchronous callbacks. Instead of assigning the var message = getMessageFromServer(), you should instead set the $('.result') from within the success callback.


getMessageFromServer();

function getMessageFromServer() {

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

    return result;
}
André Tzermias
  • 1,172
  • 10
  • 13