2

i have below given array as my ajax response, now i want to append these array values in my html div for this i have used for loop but whats going wrong ? i am getting below output (see attached image)

//Array from php page
Array ( 
[FirstName] => Please enter your first name 
[LastName] => Please enter last name 
[Email] => This e-mail address is already associated to another account. 
[ConfirmPassword] => Passwords do not match 
)

//jquery
success:function(result){
for (var i = 0; i < result.length; i++) 
{
  console.log(result[i]);
  $("#error_div").append(result[i]);
}
  }

//want this output to append in div
Please enter your first name 
Please enter last name 
This e-mail address is already associated to another account.
Passwords do not match

enter image description here

0

2 Answers 2

6

There is no associative array in javascript, it's a just an object with properties.

If you would like to iterate this object you can use a for...in loop:

for (var key in result) 
{
  console.log(result[key]);
  $("#error_div").append(result[key]);
}

You can also use a for...of loop with Object.values() to get the value directly:

for (let value of Object.values(result)) 
{
  console.log(value);
  $("#error_div").append(value);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Or for(let key of Object.keys(obj)).
1

Javascript has no associative arrays. You could loop over the object, but since you are using jQuery anyway you could use each(). If performance matters, use a for loop tho.

var values = {
    'FirstName': 'Please enter your first name ',
    'LastName': 'Please enter last name ',
    'Email': 'This e-mail address is already associated to another account. ',
    'ConfirmPassword' : 'Passwords do not match '
};

var errors = $('#error_div');
$.each(values, function( index, value ) {
  errors.append(value);
  errors.append('<br>');
});

JSFiddle

1 Comment

it's not working , see the attached image in my question, after using your answer i got that.

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.