Ravi Khakhkhar
Ravi Khakhkhar

Reputation: 1964

anonymous js function with xhrpost dojo not returning data

var cType = function(templateId){
        dojo.xhrPost({
            url : "/mediation1.0.1/template/getCollectorType",
            handleAs : "text",
            headers : {"Content-Type":"text/html"},
            postData : templateId,
            load: function(data){
                    return data;
            }});
    };

When I call this function with cType(withSomeId), I get undefined. Even When I take local variable and assign data to that variable, returning thatvariable also not helping.

Upvotes: 0

Views: 963

Answers (1)

Craig Swing
Craig Swing

Reputation: 8162

The problem is that your cType function does not return anything.

var cType = function(templateId){
    dojo.xhrPost({
        url : "/mediation1.0.1/template/getCollectorType",
        handleAs : "text",
        headers : {"Content-Type":"text/html"},
        postData : templateId,
        load: function(data){
                return data; 
                // this returns from the the load 
                // function, not the cType function!
        }});

    // You are not returning anything from the cType function.
 };

You should be using dojo.Deferred to accomplish what you are trying to do:

var cType = function(templateId){
  var xhrArgs = {
        url : "/mediation1.0.1/template/getCollectorType",
        handleAs : "text",
        headers : {"Content-Type":"text/html"},
        postData : templateId
  };

  return dojo.xhrGet(xhrArgs);
};

var deferred = cType('templateId');
deferred.then(
  function(data){
      // do something with the data...
  },
  function(error){
      // handle an error calling the server...
  }
);

http://dojotoolkit.org/reference-guide/1.7/dojo/xhrGet.html (This has an example that shows the deferred technique)

http://dojotoolkit.org/reference-guide/1.7/dojo/xhrPost.html

Upvotes: 2

Related Questions