Why do you want to break the asynchronous nature that Ajax was literally designed to have? "Problems" like these have been repeatedly asked on StackOverflow. But the one key thing they forget is that Ajax was designed to be asynchronous, and by trying to use the data outside of the function you're somewhat breaking that rule.
TL;DR: Ajax was designed to be asynchronous, lets keep it that way.
If you want to keep a neat structure, define a handler.
function handler(data) {
// Handle data
console.log(data)
}
$.ajax({
url: "http://localhost",
type: "POST",
data: {'example':true},
success:handler
});
I do not advise this method, read the above on why not.
If you truly need to perform a synchronous Ajax request (sjax? Lol, jQuery does provide a feature to "turn off the asynchronous nature", using the async: false
in the object appears to solve that. Here is an example:
var outterData;
$.ajax({
async: false,
url: "/echo/json/",
data: {testing:true},
success: function(data){
outterData = data;
}
});
console.log(outterData);
As you can see, async: false
was included in this. And it appears to work fine, based on this JSFiddle a built.
But remember, I don't advise you take away the asynchronous nature of Ajax (it's in the name, for crying out loud). But if you must.