I know it sounds like something that's been asked before, but for all my hunting, I can't find anything matching what I'm looking for.
I'm working on a project that's rather heavily based on Ajax. I'm using jQuery, but even with its beautifully streamlined code, it's still messy when I've got it to the point that the code is exactly the same, except for one single command passed through the data
field.
So I tried setting it up inside a handler function, like so:
function _call(task, opts, async) {
if(typeof async !== "boolean") { async = true; }
opts = $.extend({}, opts, options);
$.ajax({
url: "myphpfile.php",
dataType:"JSON",
type:"POST",
async:async,
data: { task: task, opts: opts }
}).done(function(data) { return data; });
}
For those who read through, you'll notice that there's a var,
options
, that hasn't been defined in the example. It has actually been assigned, it's just been omitted for clarity purposes.
I came to realize that this doesn't work, as even when it's set to async: false
, the code still continues after the call of _call(...)
, therefore not getting the results in time. I've tried a few different variations, including passing an anonymous function to the handler and then using that as the .done()
function, but it wouldn't interact with outside variables, defeating the purpose.
All I'm looking for is a system that will let me use it something like this:
var returnedData = _call("thisismytask");
var returnedDataWithOptions = _call("thisisanothertask", {'option': 'option1'});
I really hope this is possible. I'm sure it would be, as the main purpose of functions is to remove the need for unnecessarily repeated code.
Thanks. :)