-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.

2
  • mailchimp_api_key is not defined … if it isn't defined then it doesn't have anything stored in it. Commented Oct 31, 2017 at 10:28
  • But it does. Since mailchimp_api_key on its own has whatever its written in input Commented Oct 31, 2017 at 10:29

2 Answers 2

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]
}
Sign up to request clarification or add additional context in comments.

3 Comments

I didn't know you can't use it immediately in ajax call. Thanks
This has nothing to do with Ajax calls. It is just the basics of how object literals work.
I meant *objects
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.