JQuery - cannot set css property in ajax callback function

I'm trying to get a jquery ajax callback function to update the background color of a table cell, but I can't seem to get it to work.

I have the following code (which does not throw errors in Firebug):

$(".tariffdate").click(function () {
   var property_id = $('#property_id').attr("value");
   var tariff_id = $('#tariff_id').attr("value");
   var tariff_date = $(this).attr("id");
   $.post("/admin/properties/my_properties/booking/edit/*", { property_id: property_id, tariff_id: tariff_id, tariff_date:  tariff_date },
function(data){
   var bgcol = '#' + data;
   $(this).css('background-color',bgcol);
   alert("Color Me: " + bgcol);
});

      

I added a warning just to confirm that I am returning the expected data (6-digit hex) and I am - but the background of my table cell stubbornly refuses to change.

All table cells are of the .tariffdate class, but also have a unique identifier.

As a test, I tried to create a hover function for this class:

$(".tariffdate").hover(function () {
   $(this).css('background-color','#ff0000');
});

      

This works well, so I'm really confused as to why my callback function isn't working. Any ideas?

0


a source to share


2 answers


In the AJAX-processed handler, the instance is this

changed to an ajax object. You need to keep an instance this

for an object and use that object. For instance:



$(".tariffdate").click(function () {
   var property_id = $('#property_id').attr("value");
   var tariff_id = $('#tariff_id').attr("value");
   var tariff_date = $(this).attr("id");
   var tariff = $(this);
   $.post("/admin/properties/my_properties/booking/edit/*", 
      { property_id: property_id, tariff_id: tariff_id, tariff_date:  tariff_date },
      function(data) {
         var bgcol = '#' + data;
         tariff.css('background-color',bgcol);
         alert("Color Me: " + bgcol);
      }
   );
});

      

+2


a source


Check that the "this" variable is in your ajax callback function. I suspect this is not the case for .tariffdate



+1


a source







All Articles