jQuery - encountering issues setting CSS properties within an AJAX callback function

I'm struggling with a jquery ajax callback function to change the background color of a table cell. Despite no errors in Firebug, my code isn't working as expected.

Here's the code I have:

$(".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've added the alert to confirm that I'm getting the correct hex code as expected, but still, the background color of my table cell won't change.

All table cells share the .tariffdate class, but also have unique IDs.

In a test, I tried creating a hover function for that class:

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

The hover function works fine, which makes me even more confused about why the callback function isn't working. Any suggestions?

Answer №1

Within the AJAX completed handler, the context of this is altered to refer to the ajax object instead. To ensure you retain access to the original context of this, it is advisable to store it in an object and make use of that object within the handler function. Here is an example:

$(".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);
      }
   );
});

Answer №2

Verify the value of the "this" variable within your AJAX callback function. It seems like it may not be pointing to the .tariffdate element.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve JSON object by matching another JSON property

I am working with an array of id's and their respective contents in a JSON response. My goal is to retrieve the content based on the received id. For instance, if the ID is 1 (returned from the JSON), I aim to access the JSON data using "data.id" (wh ...

The add to cart feature of Ajax is malfunctioning and failing to add products to the cart

*One issue I encountered with my Ajax add to cart functionality is that the product does not get updated in the shopping cart after clicking on checkout/continue in the popup. Instead, it redirects to a specific URL * To address this problem, I utilized ...

Create a selection menu in an HTML dropdown list using unique values from a JSON object that is separated by commas

I'm working with a JSON object that contains multiple key value pairs, one of which is the Languages key. This Languages key holds comma-separated values such as "English, Hindi, French," and so on. My goal is to extract distinct values from the Lang ...

parsing an array using jQuery's getJSON

Finally got the simplified array to work, check it out below If you're still struggling with parsing a complicated array, you can refer to this link. TLDR: I need to extract and insert each heading from an array into a div using Jquery - getJSON, wi ...

Inquiring about building a comprehensive AJAX website: SEO, Google index, design templates

I'm currently developing a fully AJAX-based website. My focus right now is on implementing page navigation and content display without the need for page reloading. Here's my approach: <html> <head> <!--CSS--> .hidde ...

Achieving equal heights for div boxes while aligning list items inside

I have 8 green boxes on my site, each containing an image and either 3 or 4 list items with text only. The issue I'm facing is that the boxes are not of equal height due to two reasons: (1) One box may have an extra list item pushing the rest down, or ...

What is the process for creating this image using HTML and CSS?

Looking to style an image using HTML and CSS. This is what I attempted: <span>$</span><span style="font-size: 50px;">99</span><span style="vertical-align: text-top;">00</span> However, the result doesn't ma ...

unique jquery plugin accesses function from external javascript file

As a beginner, I am attempting to create a custom jQuery plugin for which I have a simple HTML form: <form id="registerForm" action = "somepage" method="post" class="mb-sm"> <div class="form-group"> <div class="col-md-12"> ...

Preventing multiple selections in Jquery Selectable using drag-and-drop functionality

Is there a way to disable the multiselect option when dragging with the mouse, but still allow users to select multiple items one by one while holding down the control key? The issue I am facing is that when sending an ajax service call in the select eve ...

After the ajax call has finished loading the page, I would like to toggle a particular div

When I trigger a click event on an element, it calls a function with Ajax calls. How can I toggle a div (which will be loaded after the Ajax call) once the page is loaded? function triggerFunction(){ $("#trigger_div").trigger("click"); $("#to ...

ajax event malfunction

My current issue involves an ajax event that is activated when I press the submit button to input data into a database. Originally, these elements were spread across separate files for testing purposes. Now that all the code has been consolidated, I have ...

Troubleshooting CSS Navigation Drop Issue Specific to Google Chrome. Seeking Feedback on Rails Tutorial Experience

I'm currently working my way through the amazing Rails Tutorial and have encountered a problem with the Navigation bar dropping down into the body of the page, but this issue only seems to occur in Chrome (I'm using Linux, Ubuntu 10.10). I'v ...

Tips to swap selections in a Select2 dropdown box

Is there a way to dynamically clear a Select2 option list and reload it with new data? Despite setting the data as suggested, it seems to only append the new data without clearing the existing options. $("#optioner").select2(); $("#doit").click(functio ...

Encountering a 404 error when attempting to upload information to the database

Currently, I have the ability to upload a CSV file with one column per row. My goal now is to read the contents of this file and pass it as data to an AJAX call. Below is my current code snippet: var addPortfolio = function(){ console.log("I ...

JQuery datepicker is functioning properly only after an alert when loaded with AJAX

Here's a puzzling question I have encountered. I implemented a field with a datepicker functionality. This field gets loaded into a div through an AJAX call. To sum it up, everything seems to be in working order.. But there's a strange issue. I ...

"Learn how to position a div element below the header div and above the footer div while maintaining full height in

Recently delving into the world of reactjs, I find myself facing a challenge with a page that contains 3 distinct blocks formed by divs. Have a look at the layout on my page: My Page This is the code snippet I have worked on: return ( <div> ...

Exploring the benefits of the AjaxHelper class in conjunction with jQuery within asp.net mvc applications

I've incorporated jQuery and jQuery UI throughout my project using HtmlHelper extensions, but for some reason I haven't fully grasped the benefits of utilizing the AjaxHelper. (or maybe I'm just unaware) I'm intrigued to learn about the ...

assigning a variable using jQuery

<script> function update(elem) { var ele=$(elem).siblings('label#test').html(); var a=document.getElementById('test'); var htm = '<input type="text" name="modal" id="modal" style="width:70%;" value="'+$(elem).siblings ...

Sending information from a controller to a view in Ruby: a how-to guide

Currently, I am utilizing Ruby and facing the need to provide users with a constant status update message while a lengthy task is executed in the controller. During this method, various rows are being inserted into the database. My goal is to display a me ...

Could a complex, intricate clipping path be created using CSS 3?

Here is an example: Can this be achieved using only CSS? I wish to create two divs: A circle without any background or border. A div with a background. I aim to have point 1 clip the background from point 2. This will allow me to rotate the backgroun ...