0

I am trying to get the value of the attribute 'data-tablename'.

$.ajax({ 
  type: 'post', 
  url: "<?= base_url(); ?>table/moveTable/",
  data: "table_name=" + $(this).attr("data-tablename"), 
  success: function(r) {
      $.notify($(this).attr("data-tablename") + " was successfully added", "success");
  }
});

When I try this code, I get the message "undefined was successfully added"

How can I get the value of it?

Reza Saadati
  • 5,018
  • 4
  • 27
  • 64
  • Well, `this` in that context is the ajax function, and why would the ajax function have a data attribute ? – adeneo Apr 03 '15 at 21:02

3 Answers3

2

Add var tableName = $(this).attr("data-tablename"); before ajax invocation and then replace $(this).attr("data-tablename") with tableName variable

Oleks
  • 1,633
  • 1
  • 18
  • 22
1

You should assign $(this) to a variable before the ajax action, and then use that variable in the anonymous functions:

var $this = $(this);

$.ajax({ 
  type: 'post', 
  url: "<?= base_url(); ?>table/moveTable/",
  data: { "table_name": $(this).attr("data-tablename") },
  success: function(r) {
      $.notify($this.attr("data-tablename") + " was successfully added", "success");
  }
});
Hamid Mohayeji
  • 3,977
  • 3
  • 43
  • 55
1

Whenever you have a function defined in another function, this in the inner function will not be the same as the outer function unless there is something to specifically set it to be so. In this case you can use jQuery.ajax's context configuration, this sets the value of this in all the callbacks to whatever you want.

$.ajax({ 
  type: 'post', 
  url: "<?= base_url(); ?>table/moveTable/",
  data: "table_name=" + $(this).attr("data-tablename"), 
  context: this,
  success: function(r) {
      $.notify($(this).attr("data-tablename") + " was successfully added", "success");
  }
});
Musa
  • 96,336
  • 17
  • 118
  • 137