0

Totally new to OOP in javascript, but Im trying and reading all I can.

Ive created a simple test javascript class called Invoices. Invoices only has two methods. One method fires the other. And this part seems to be working fine.

My problem lies with getting data objects from one method to another. I put a alert in the first method, (from my understanding) this alert should show data returned from the second method... but its not.

Any help would be greatly appreciated. Oh.. and I am using jquery as well.

Here is my codez.

 function Invoices()
 {
  this.siteURL = "http://example.com/";
  this.controllerURL = "http://example.com/invoices/";
  this.invoiceID = $('input[name="invoiceId"]').val();
 }

 invoice = new Invoices;

 Invoices.prototype.initAdd = function()
 {
  //load customers json obj
  this.customersJSON = invoice.loadCustomers();
  alert(this.customersJSON);

  //create dropdown
 }

 Invoices.prototype.loadCustomers = function ()
 {
  $.post(this.controllerURL + "load_customers"),
  function(data)
  {
   return data;
  }
 }

2 Answers 2

2

There are two problems with that. First of all, $.post is asynchronous; you'll have to adopt a callback scheme or use $.ajax to make it synchronous. Secondly, you probably meant to do this:

$.post(this.controllerURL + "load_customers", function(data) {
    return data;
});

Note how the closure is in the parentheses of the function call.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response. I fixed that syntax error. The post part is actually working. I can see the XHR request and json response, however, the alert is still saying undefined.
@Peter - I don't get why you say there is a json response but alert is undefined. How did you see the json? are you alerting the json data?
0

As you were told the AJAX call is asynchronous, you would have to implement your initAdd in 2 step:

  1. BeginInitAdd which would initiate the AJAX call
  2. EndInitAdd which would be the callback for your AJAX call and perform the action depending on the data returned.

Invoices.prototype.initAdd = function()
{
    //load customers json obj
    this.xhrObj = invoice.loadCustomers();
    alert(this.customersJSON);
}
Invoices.prototype.createDropdown = function (data) {
    //create dropdown
    this.customersJSON=data
}
Invoices.prototype.loadCustomers = function ()
{
    return $.post(this.controllerURL + "load_customers"),
    function(data)
    {
        //return data;
        this.createDropdown(data)
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.