I am trying to create a function that produces AJAX calls and returns the response.
function msg(message)
{
send = new XMLHttpRequest();
send.open("POST", "msghandler.php", false);
send.setRequestHeader("Content-type","application/x-www-form-urlencoded");
send.send("msg="+encodeURI(message));
return send.responseText;
}
As you can see, right now I am using a synchronized call, but this isn’t an optimal solution because it is very common in my debugging for something to go wrong on the server side and end up freezing my browser. Is there a way to make the call asynchronous and have the response be returned by the function?
You can’t return something that doesn’t exist. But you can return a promise object if you are afraid of indenting callbacks in eternity. Here is a very simple example:
Many frameworks already implemented deferred objects.