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
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
Share
Improve this question
edited Aug 2, 2015 at 15:30
amit gupta
asked Aug 2, 2015 at 14:27
amit guptaamit gupta
1,3302 gold badges21 silver badges36 bronze badges
0
2 Answers
Reset to default 6There 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);
}
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