0

I've been trying to get this to work for hours now.

I'm trying to get each input with .textinputclass, combine them together and via ajax putting that into a database.

Two tings are working seperate, I can get each input and put those together in the format that i want.

and I can use .post to send data to a php script to put it in the database

$(".addSubmit").click(function(){ $('.textinputclass').each(function(){ var textData = $(this).val(); var thisLanguage = $(this).attr('id'); var textData = '[:' + thisLanguage + ']' + textData; languagearray.push(textData); }); var nameData = 'test1111'; var textData = languagearray.join(''); var languagearray = []; var data = { 'name' : nameData, 'text' : textData }; $.post('../wp-content/plugins/qtranslate-hardcodedtext/additem.php', data, function() { alert('done!'); }); }); 

if I remove the .each function and just put text in the data array then the .post works.

3
  • @Elfayer there's no synchronisation needed here - when won't help Commented Jul 11, 2014 at 10:18
  • Please describe how it fails when the .each loop is in place? The use of post is probably a red herring - most likely the loop simply isn't creating the values you think it is. Commented Jul 11, 2014 at 10:19
  • Did you check the value of "data" variable just before posting it? Something can be wrong inside the loop Commented Jul 11, 2014 at 10:20

2 Answers 2

2

I think you must create an array languagearray. http://jsfiddle.net/FFr5z/

Edit:

var languagearray = []; $('.textinputclass').each(function(){ var textData = $(this).val(); var thisLanguage = $(this).attr('id'); var textData = '[:' + thisLanguage + ']' + textData; languagearray.push(textData); }); 
Sign up to request clarification or add additional context in comments.

1 Comment

technically the OP did declare the variable languagearray - what he failed to do was initialise it do an empty array before trying to use it.
1

Your issue is the definition of languagearray.

Although you have correctly declared it, that declaration is after the .each loop.

The net result is that the declaration (but not the initialisation) of languagearray is "hoisted" to the top of the function, making it available in the entire scope, but its initial value is just undefined instead of [].

As the variable is undefined, you can't call push on it, which should have been evident within your browser's JS console.

2 Comments

Thanks, the array after the loop was supposed to be to clear the array but i forgot to declare it before the loop. I now declared it before the function and used languagearray.length = 0; to clear it.
@NickH yes, I guessed that you were trying to erase the array. However there's actually no need to do so - the garbage collector will get rid of it automatically when it needs to.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.