views:

211

answers:

2

Why does this script result in 'undefined' when the value is returned from the Ajax call?

function myShippingApp() {

this.shipper = 0;

this.init() {
 this.getShipRate();
 alert(this.shipper);
}

this.getShipRate = function() {

 var zip = $('zip').value;
 if(zip == '') {
  return false;
 } else {
  var url = 'getrate.php?zip='+zip;
  this.shipper = new Ajax.Request(url, {
   onComplete: function(t) {
    $('rates').update("$"+t.responseText);
    return t.responseText;
   }
  });
 }
}

}

I'm working with Prototype framework, and having trouble returning the value back to object. What am I doing wrong?

Thank you!

A: 

Ajax.Request doesn't return any value, it's an instantiation of an object.

I guess you can say that the value is the object itself.

Luca Matteis
+2  A: 

The value you want is in t.responseText, it doesn't get 'returned' by the Ajax.Request object, thus this.shipper is never assigned its value.

This is probably more along the lines of what you want:

function myShippingApp() {

  this.shipper = 0;

  this.init() {
    this.getShipRate();
  }

  this.getShipRate = function() {
    var zip = $('zip').value;
    if(zip == '') {
      return false;
    } else {
      var url = 'getrate.php?zip='+zip;
      new Ajax.Request(url, {
        onComplete: function(t) {
          $('rates').update("$"+t.responseText);
          this.shipper = t.responseText;
          alert(this.shipper);
        }
      });
    }
  }
}

Let me know if it works for you.

Dustin Fineout