1

In my case, I have a parent div which have multiple child div. These child div are generated according to $.each() function.

Number of times function run, num of div get generated.These child div contains data like-- UserId, UserName, UserPic and a follow button.Now, i want to write a server side function on button click and post the UserId to controller.

Now, i have seen many so questions and solution was to have a global variable and assign value to that variable from your $.each function.But, in my case, my $.each function will loop several times so how to get back particular item.Id when a follow button is clicked and post back that value to controller

$(document).ready(function() {
var parent = $(".div1");

$.getJSON("/Home/GetUsers", null, function(data) {
  parent.html("");

  $.each(data, function(i, item) {
    var html = "<div class='div2'>";
    html += "Name: " + item.UserName + "<br />";
    html += item.ArticleCount;
    html += "<img src='" + item.UserImage + "'height='20px' width='20px'/>";
    html += "<button type='button' class='newButton'>Click Me!</button>";
// wants to send current userId on button click 
    html += item.Id;
    html += "</div>";
    parent.append(html);
  });
});
parent.on('click', '.newButton', function(e) {
   var button = $(this);
    var html = "<div class='listItem'>";
                   $.ajax({  
                           type: "POST", 
                           url: "Home/Follow", // Controller/View   
                           data: { //Here, i am struck, how to get back                      correct userid from above $.each function
                           id: $(".listItem").    
                  }  
});
});
duke
  • 1,476
  • 1
  • 13
  • 24

2 Answers2

1

You can store id in every button using data attribute data-id for example :

html += "<button data-id="+item.Id+" type='button' class='newButton'>Click Me!</button>";

And you can get the id when the button clicked like :

$.ajax({  
     type: "POST", 
     url: "Home/Follow", // Controller/View   
     data: { id: $(this).data('id') }
});

Hope this helps.

Zakaria Acharki
  • 63,488
  • 15
  • 64
  • 88
  • 1
    `$(this)` inside $.ajax causes `this` to point to the object being passed instead of the clicked element. –  Dec 30 '15 at 10:45
  • 1
    @nightgaunt No, its not. `this` is the context of the calling function which is the clicked button. [fiddle](https://jsfiddle.net/6hew1wr7/) – Andreas Dec 30 '15 at 10:53
  • You're right @Andreas it will not work inside the `success` function. – Zakaria Acharki Dec 30 '15 at 10:55
  • @nightgaunt [How does the "this" keyword work](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Andreas Dec 30 '15 at 10:55
  • can u tell me please data-id="+item.Id+" and data: { id: $(this).data('id') how these two r communicating many thnks in advance @ZakariaAcharki – duke Dec 30 '15 at 11:11
  • 1
    `data-name_of_data=value` will add an attribute `data` like (class, id ...) with name `name_of_data` to the tag and asign `value` to it, now when you want to get the data attribute from the tag you get it using `data(name_of_data)` like in our case we have `id` so we can get it `tag.data('id')`. – Zakaria Acharki Dec 30 '15 at 11:16
  • 1
    Yes. Tried it in console with an example and @Andreas is correct. As @ZakariaAcharki pointed out, inside success function `this` won't work. Apologies for misdirection. –  Dec 30 '15 at 11:57
0

You can add the item.Id value as Id or any data-* attribute to the button. And on click you can retrieve the value.

Also you can just create one string rather than doing html +=

So I have modified the code and here is the snippet

$(document).ready(function() {
var parent = $(".div1");

$.getJSON("/Home/GetUsers", null, function(data) {
  parent.html("");

  $.each(data, function(i, item) {
     // Refactored DOM
    var html = "<div class='div2'>Name: " + item.UserName + "<br />"+item.ArticleCount+
                   "<img src='" + item.UserImage + "'height='20px' width='20px'/>"+
                      "<button type='button' class='newButton' id = '"+item.Id+"'>Click Me!</button>"+
                        item.Id+"</div>";

            parent.append(html);
      });
});
parent.on('click', '.newButton', function(event) {
   var getId = event.target.id;  // Event object will give all parameters you need 
   alert(getId);
    var html = "<div class='listItem'>";
                   $.ajax({  
                           type: "POST", 
                           url: "Home/Follow", // Controller/View   
                           data: { id: getId}   // Added the required Id  
});
});

Hope this will be useful

brk
  • 43,022
  • 4
  • 37
  • 61