cjm2671
cjm2671

Reputation: 19466

jQuery variable scope? says undefined

I have the following code:

function postToDrupal(contacts, source, owner) {
  (function ($) {

    var contact, name, email, entry;
    emails = {};

    for (var i = 0; i < contacts.length; i++) {
      contact = contacts[i];
      emails[i]['name'] = contact.fullName();
      emails[i]['email'] = contact.selectedEmail();
    }

    $.post("/cloudsponge-post",emails,function(data) {

    });
  }(jQuery));
}

I get the following error when I try and run it:

WARN: Attempt to invoke callback [afterSubmitContacts] failed: TypeError: Cannot set property 'name' of undefined

I'm not sure what the problem is- I'm quite new to JS and finding it a bit tricky. What's the reason it's broken, and how do I go about fixing it?

Upvotes: 1

Views: 276

Answers (3)

Marlon Bernardes
Marlon Bernardes

Reputation: 13853

I suspect you want an array instead of an object. So you should change emails = {} to emails = [].

If you do as @PSL suggested you will end with an object like this (which is not an array):

{
  0: {
    name: 'john'
    email: '[email protected]'
  },
  1: {
    name: 'lennon'
    email: '[email protected]'
  }
}

One possible solution:

var contact, name, email, entry,
  emails = [];

for (var i = 0; i < contacts.length; i++) {
  contact = contacts[i];
  emails.push({name: contact.fullName(), email: contact.selectedEmail()});
}

You'll end up with this:

[
  {
    name: 'john'
    email: '[email protected]'
  }
  ,{
    name: 'lennon'
    email: '[email protected]'
  }
]

Upvotes: 0

Michael Geary
Michael Geary

Reputation: 28860

There are a bunch of ways you could write this code, but personally I would do this:

function postToDrupal( contacts, source, owner ) {
    // TODO: source and owner are unused

    var emails = jQuery.map( contacts, function( contact ) {
        return {
            name: contact.fullName(),
            email: contact.selectedEmail()
        }
    });

    jQuery.post( '/cloudsponge-post', emails, function( data ) {
        // ...
    });
}

Upvotes: 3

PSL
PSL

Reputation: 123739

That object emails[i] is not yet defined. try this way:

for (var i = 0; i < contacts.length; i++) {
  contact = contacts[i];
  emails[i] = {}; //Instantiate it here
  emails[i]['name'] = contact.fullName();
  emails[i]['email'] = contact.selectedEmail();
}

Upvotes: 2

Related Questions