Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX response using HTML5 data attribute

I've a working env where I'm using AJAX response to fill in HTML elements.

for example AJAX response has two(or n) objects like this:

0:Object
     id: "111"
     Name: "abc"
1:Object
     id: "112"
     Name: "xyz"

Then, There already would be two(or n) divs with user class and HTML5 data-user containing the id in HTML

<div class='user' data-user='111'>
    <div class='userId'data-userId='111> </div>
     <div class='usernm' data-user='usernm'> </div>
</div>

<div class='user' data-user='112'>
    <div class='userId'data-userId='112> </div>
     <div class='usernm' data-user='usernm'> </div>
</div>

What I need is put those response values in this divs like this:

<div class='user' data-user='111'>
    <div class='userId'data-userId='111> 111 </div>
     <div class='usernm' data-user='usernm'> abc </div>
</div>
 <div class='user' data-user='112'>
    <div class='userId'data-userId='112> 112 </div>
     <div class='usernm' data-user='usernm'> xyz </div>
</div>

What I'm currently doing (and is working) is using jQuery find (see below code) but now I'm suggested to put the responses using HTML5 data-.. attribute. I can't get around it, if someone can help up with it..

$.ajax({
    type: 'GET',
    url: '/url/goes/here',
    dataType: "json",
    success: function(data) {
       $('.user').each(function(key, value){ //i need to remove .user and use data-user here (if possible)
            $(value).find('.userid').text(data[key].id); //i need to put values using data attr instead of find
            $(value).find('.usernm').text(data[key].name); //i need to put values using data attr instead of find              
       });
    }
});
like image 382
s develop Avatar asked Jul 31 '26 18:07

s develop


1 Answers

Data attributes are accessed by:

$(#id).data('userId');

or

$(#id).attr('data-userId');

and to set a value in that data attribute:

$(#id).data('userId', 'value');

or

$(#id).attr('data-userId', 'value');
like image 53
Mayank Pandeyz Avatar answered Aug 03 '26 07:08

Mayank Pandeyz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!