I have a big problem and no idea how to solve it.
I need to return values (mostly strings) to use them in various contexts. As an example, I need to check whether something is 0 or 1 in an if/else statement or insert a string in various html elements before parsing it via JavaScript into the DOM. Here is a simplified example of what I’m looking for:
<script>
function output() {
return "Hello world!";
}
function check() {
return 3;
}
(function() {
if(check() !== 5) {
$(someElement).set("html", "<p>" + output() + "</p>");
}
})();
</script>
Now lets get into the headaching part: Before returning the value, I need to request it from a JSON context in an external file that loads the contents from the backend. I wrote a class that contains the Request.JSON MooTools class to make it easier to use with various requests:
<script>
var backendCall = new Class({
Implements: Options,
options: {
url: "gateway/?contentType=application/json"
},
initialize: function(options) {
this.setOptions(options);
if(!instanceOf(this.options.prms, Array)) {
this.options.prms = [];
}
this.fire();
},
fire: function() {
new Request.JSON({
data: JSON.encode({
"methodName": this.options.req,
"parameters": this.options.prms,
"serviceName": this.options.srv
}),
onFailure: function() {
alert("JSON-Request failed.");
},
onSuccess: function(data) {
this.callback(data);
}.bind(this),
url: this.options.url
}).send();
},
callback: function(data) {
alert(data); // works
}
});
function request(req, srv) {
new backendCall({
req: req,
srv: srv
});
}
window.addEvent("load", function() {
/* is there a way to return the data string here?
or is it impossible? */
request("someValue", "demoTest");
});
</script>
This works great when executing a hardcoded function inside the callback function that refers the JSON-Request output. But I need to make this part more variable because I want to use the output in different ways. Is there a way to let the callback just return the output and refer it to the parent request() function to let it return the value? Maybe with .pass(data)? Any ideas are welcome! Thank you so much! 🙂
well. XHR is async (ajax) so you can only get the value as a callback on the
onCompleteevent.typically, you wait for the response and the onComplete can then go to the next item you are checking or finalise.
eg, in pseudo code:
of course, you can set the
async: falseon the request object, which will block UI until it completes so the onComplete can set your var and the line immediately after the Request.send() will have it available to use.you can do a proper validator (or use a ready made one) which defines a ruleset and checks them in order, understanding async onComplete and having a stack of checks to work against, there are many examples of this and even mootools-more has a form-validator that’s pretty extensive (though I have not used it myself so cannot testify on how it deals with async checks)