I have one for
loop that gets data from the server sorted descending, but in append()
the data sort is not working. For example, the first row show in second position.
How can I append data exactly as it's sorted from the server side data?
$(document).on('click', '#jhchat', function() {
$('.jhchat').find('.messagemoda').html('');
var jus = '{{Auth::user()->id}}';
$.ajax({
url: '{{url("getuchats")}}',
type: 'post',
data: {
_token: CSRF_TOKEN
},
success: function(data) {
if (data.length > 0) {
for (var i = 0; i < data.length; i ) {
if (data[0].s_id == jus) {
var mid = data[i].r_id;
} else {
var mid = data[i].s_id;
}
$.ajax({
url: '{{url("getchatdet")}}',
type: 'post',
data: {
_token: CSRF_TOKEN,
'mid': mid,
'chid': data[i].id
},
success: function(res) {
$('.jhchat').find('.messagemoda').append(`
<div hljs-property">chat.id `" alt="` res.chat.id `">
<div hljs-property">chat.id `" alt="` res.chat.id `" id="` res.mid `">
<div style="padding-left: 5px;">
<img src="` res.img `" alt="home" width="60" height="60" >
</div>
<div >
<h6 >` res.name ' ' (res.mescount > 0 ? '<span style="color: crimson;background-color: bisque;border-radius: 50%;padding-left: 5px;padding-right: 5px;">' res.mescount '</span>' : '') `</h6>
</div>
</div>
<div style="position: relative;">
<img src="{{url('images/menu.png')}}" alt="` res.chat.id `" width="32px" height="32px" style="cursor: pointer;background-color: #eee;border-radius: 50%;padding:8px;">
<div hljs-property">chat.id ` jsmen">` (res.justo > 0 ? '<a href="' res.s '">go store <img style="margin-right: 2rem;" src="{{url('images / arrow1.png ')}}" width="13px" height="13px"></a>' : '') `
<p alt="` res.chat.id `" style="cursor: pointer;">delete <img style="margin-right: 3.4rem;" src="{{url('images/close1.png')}}" width="10px" height="10px"></p>
</div>
</div>
</div>`);
}
});
}
$(".messagemoda").trigger("update");
} else {
$('.jhchat').find('.messagemoda').html('<div >no data</div>');
}
}
});
$('.adsopa').css('opacity', '0.3');
$('.sidebarmenu').removeClass('active');
$('.jhchat').css("display", "block");
$('body').css('overflow-y', 'hidden');
});
CodePudding user response:
You are reverting the sorting with append after .messagemoda
. So if server is returning element A and B, it first appends A (ok for now) and you get .messagemoda
, A. After you append B after .messagemoda
, you get .messagemoda
, B, A. So you have to append after the last element from server if it exists or after .messagemoda
, if there are no elements present.
And as pointed out in the comments, you should get all data in one request if you have the backend, which can provide it as such. These multiple request could not be received in the order you send them - you have no control over the magic of the network if self.
CodePudding user response:
i fetch all of the data need with a single request and problem is solved thanks every one to help and guid