dave dave - 4 months ago 11
Ajax Question

Ajax php array data loading all in one div and has commas

this is my first time working with ajax in the new world lol.. Its been a very long time since i have seen it and it has changed..

The problem i am having is that the data is all ending up in one div instead of accross the page in three divs. If i load the divs manually it comes out fine, but when i switch to ajax its all in one div and the data is comma seperated as well. I think it might have something to do with the way i am handling the array. But i have no experience in ajax working with arrays this way.

The comma seperated data is all ending up in the first div and i dont need the commas either.

here is the array (the first two elements i combine in the first div - name image)

Array
(
[0] => Array
(
[0] => testprofile
[1] => http://www.example.com/dirname/dirname/dirname/images/no-avatar.png
[2] => adad
[3] => 02:32:08
)

)


here are the html divs

<td align="center" width="20%"><div id="userdata"></div></td>
<td width="70%"><div id="mesdata"></div></td>
<td align="center" width="10%"><div id="timedata"></div></td>


here is the ajax

function ajaxGetMessages(roomid, urlwithr)
{
$.ajax({
cache: false,
dataType: 'json',
method: 'GET',
url: urlwithr,
data: {
roomid: roomid,
urlrnd: urlwithr,
ajax: true
},
success: function(data) {

data.forEach(function(entry) {

var alphaname = data[0];
var avatar = data[1];
var displayuser = alphaname+'&nbsp;<img src="'+avatar+'" alt="avatar" height="30" width="30" />';

document.getElementById("userdata").innerHTML = displayuser;
document.getElementById("mesdata").innerHTML = data[2];
document.getElementById("timedata").innerHTML = data[3];

});//close forEach

}//close success
}); //close ajax

}//close function

Answer

data is an array of arrays. And you're looping over those arrays with forEach. function(entry) provides each sub-array to the function procedure by assigning it to the variable entry, therefore access each item within the sub-array using entry[0], entry[1], etc.

data.forEach(function(entry) {    

  var alphaname = entry[0];
  var avatar = entry[1];
  var displayuser = alphaname+'&nbsp;<img src="'+avatar+'" alt="avatar" height="30" width="30" />';

  document.getElementById("userdata").innerHTML = displayuser;
  document.getElementById("mesdata").innerHTML = entry[2];
  document.getElementById("timedata").innerHTML = entry[3];

});//close forEach
Comments