hncl hncl - 6 months ago 16
Javascript Question

Jquery each table - hide show using Ajax

My application is MVC 5, I am trying to using the following script to hide and show a button in each row based on the value I get from database using Ajax.

function setButtons() {
$('#MyList > tbody > tr').each(function () {
var typeid = $(this).find("select").val();
if (typeid != null ) {
$.ajax({
url: '/MyController/GetInfo',
type: 'POST',
data: {
id: typeid
}
})
.success(function (data) {
var tr;
if (data == null) {
$(this).find("button#Details0").hide();
} else {
$(this).find("button#Details0").show();
}
})
.error(function (jqXHR, textStatus) {
alert("error");
});
}
});


I have tested Ajax by itself, it works, I get the value from select, and receive data back from the controller. I suspect the problem could be in using "this" inside the Ajax script. Would appreciate your suggestions.

Answer

You need to assign the $(this) to a variable so in can be used in the success function

function setButtons() {
  $('#MyList > tbody  > tr').each(function () {
    var self = $(this); // store the value
    var typeid  =  $(this).find("select").val();
    if (typeid != null ) {
      $.ajax({
        url: '/MyController/GetInfo', // recommend '@Url.Action("GetInfo", "MyController")'
        type: 'POST',
        data: { id: typeid }
      })
      .success(function (data) {
        var tr; // ? not used
        if (data == null) {
          self.find("button#Details0").hide(); // change this
        } else {
          self.find("button#Details0").show(); // and this
        }
      })
      .error(function (jqXHR, textStatus) {
        alert("error");
      });
    }
  });
}

Note also jqXHR.success() and jqXHR.error() have been deprecated. Use .done and .fail instead