-1

I have this code

    var array, key, dc;
    $.post("/mailchimp/check_mailchimp_key",
    {
      store_id: document.getElementsByName('data[store_id]')[0].value,
      mailchimp_api_key: document.getElementsByName('data[mailchimp_api_key]')[0].value,
      array: mailchimp_api_key.split('-'),
      key: array[0],
      dc: array[1]
    }

store_id and mailchimp_api_key work, but I have problem with others. This way it says mailchimp_api_key is not defined and my goal is to take whatever is stored in mailchimp_api_key and divide it to key and dc.

Seinfeld
  • 433
  • 7
  • 24

2 Answers2

4
mailchimp_api_key: document.getElementsByName('data[mailchimp_api_key]')[0].value

… means that when the object has finished being constructed it will have a property called mailchimp_api_key with that value.

mailchimp_api_key.split('-'),

… tries to read a variable called mailchimp_api_key.

There are two problems with this:

  • A variable is not an object property
  • The object property doesn't exist yet

Copy the value to a variable before you construct the object.

Use it twice.

var array, key, dc;

var mailchimp_api_key = document.getElementsByName('data[mailchimp_api_key]')[0].value;

$.post("/mailchimp/check_mailchimp_key",
{
  store_id: document.getElementsByName('data[store_id]')[0].value,
  mailchimp_api_key: mailchimp_api_key,
  array: mailchimp_api_key.split('-'),
  key: array[0],
  dc: array[1]
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

This is not Javascript at all! You can't reference Object keys that you just defined.

var mailchimp_api_key  = document.getElementsByName('data[mailchimp_api_key]')[0].value;
var array = mailchimp_api_key.split('-');
var key = array[0];
var dc = array[1];

This way you get all the variables you need, then you might want to pass them in your Ajax call.

Luca De Nardi
  • 2,280
  • 16
  • 35