Update the data-value parameter dynamically after a successful Ajax request without utilizing the element's

I have a bunch of different buttons to switch the status of various projects:

<div class="btn-group btn-toggle project_status" data-project-id="1" data-form="project_status" data-value="1"> 
  <button class="btn btn-default active">ACTIVE</button>
  <button class="btn btn-primary">CLOSED</button>
</div>
<div class="btn-group btn-toggle project_status" data-project-id="2" data-form="project_status" data-value="1"> 
  <button class="btn btn-default active">ACTIVE</button>
  <button class="btn btn-primary">CLOSED</button>
</div>

After successfully posting via ajax, I need to toggle the data-value back and forth between 1 and 2.

I've attempted the following approach but haven't had any success:

$('.project_status').click(function(){
    var project_id = $(this).attr('data-project-id');
    var project_status_val = $(this).attr('data-value');
    var toggle_status = function(){
        $(this).find('.btn').toggleClass('active').toggleClass('btn-primary');
        if (project_status_val == '1'){
            alert(project_status_val);
            $(this).attr('data-value','2');
        } else {
            alert(project_status_val);
            $(this).attr('data-value','1');
        }
        return false;
    };
    var dataString = 'project_id=' + project_id + '&project_status=' + project_status_val;
    $.ajax({
        type: "POST",
        url: "post.php",
        data: dataString,
        success: toggle_status
    });
    $('#sidebar-wrapper').load('sidebar.php');
    return false;
});

I'm able to display the correct data value in the alert. The sidebar reloads with the updated value after the first click. However, I'm struggling to change the attribute value so that the next click sends the toggled value.

If you can assist, thank you!

Answer №1

$(this) inside the toggle_status function does not refer to your button. The this keyword within the function actually points to the object to which the method belongs, in this case, the Window object. To address this issue, a self property has been created before the method to hold a reference to the selected $('.project_status') object. The code has been modified accordingly for proper functionality.

https://jsfiddle.net/05akxvx3/1/

$('.project_status').click(function(){
  var self = $(this);
  var project_id = self.attr('data-project-id');
  var project_status_val = self.attr('data-value');
  var toggle_status = function(){
    self.find('.btn').toggleClass('active').toggleClass('btn-primary');
    if (project_status_val == '1'){
        self.attr('data-value','2');
    } else {
        self.attr('data-value','1');
    }
    alert(self.attr('data-value'));
    return false;
  };
  var dataString = 'project_id=' + project_id + '&project_status=' + project_status_val;
  $.ajax({
    type: "POST",
    url: "post.php",
    data: dataString,
    success: toggle_status
  });
  $('#sidebar-wrapper').load('sidebar.php');
  return false;
});

Answer №2

There is a mistake with the dash in your $(this).attr() function.

The correct format for $(this).attr('data--value','2'); should be:

$(this).attr('data-value','2');

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

Issues with Ajax causing problems with updating information in <h:selectOneMenu>

How can I update a selectOneMenu based on the selection of another selectOneMenu? I need the user menu to be dynamically updated when a group is selected. Although I can see that the data for the user menu is being updated, it's not rendering as exp ...

transforming a div to behave similarly to an iframe

I am trying to load content from my page into a div element using the following function: function loadmypage(DIV, pageURL) { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } e ...

Leveraging AngularJS $promise in conjunction with NgResource

As I delve into the world of AngularJS, I have encountered promises which have proven to be quite beneficial in my learning journey so far. Now, I am eager to explore the optional library resource.js in AngularJS. However, I stumbled upon examples that lef ...

The header row in my table multiplies each time an AJAX call is made

HeaderRowMultiplesEachTimeAjax My web grid table in JavaScript consists of a complete HTML table. The top header, which acts like a colgroup caption table, is built through JavaScript insertion as shown below: var headerRow = "<tr><th colspan=&a ...

Before sending an XHR request with Ajax, access can be granted

My goal is to implement a redirect for ajax requests. In the event of a session expiration, my backend currently redirects to the login page instead of sending data. However, I have come across discussions on StackOverflow highlighting that ajax does not h ...

What steps can I take to prevent my JavaScript code from interfering with my pre-established CSS styles?

I'm currently designing a mini-email platform that serves as a prototype rather than a fully functional application. The HTML file contains placeholder emails that have been styled to appear presentable. I've implemented an input bar and used Jav ...

Import information from a SqlServer Database into a jQuery Full Calendar utilizing the capabilities of Codeigniter3

I've been dealing with this issue for quite some time now. I used to work with the same calendar in PHP, but since my project is in Codeigniter, it's not fitting properly. Therefore, I have switched to working with Codeigniter. Controller Code ...

Querying the database to check for the presence of a file in a .js file on Google App Engine

I'm currently working on implementing an upload button for users to upload files to our storage system using Google App Engine with Python, as well as HTML and JavaScript for the views. To achieve this, we have an HTML file and a.js script that promp ...

jQuery: changing the order of list elements with the eq method

I've been tackling a challenge with designing a navigation bar that consists of 3 items. The goal is to have the clicked item move to the center position on the horizontal navbar while re-arranging the order. Here's the code snippet I've com ...

Guide to using react-router for redirection and displaying messages

Is there a way in React to redirect after a successful login with a success message displayed on another component? I previously used flash messages, but they didn't integrate well with react-router and caused full page refreshes. Now that I am using ...

"Embed" three.js within SmartMS

Is it possible to incorporate this simple three.js example into Smart Mobile Studio without extensive wrapping? I attempted to copy the window.onload content into an asm section but was unsuccessful. <!DOCTYPE html> <html> <head> <t ...

Receiving 'Unexpected end of input' error when using a string as a JavaScript function argument

I am trying to implement an ajax request function in my project. This is the code snippet I have: function Reject(id, scomment) { jQuery.ajax({ type: "POST", url: "reject.php", data: {id: id, Scomment: scom ...

Is it possible to alter the JSON file being loaded in AngularJS by passing a variable?

I am in need of loading the content from either food1.json or food2.json, and I am attempting to achieve this within the html template: <body ng-controller="MainCtrl" ng-init="init('food1')"> Subsequently, in the JavaScript code: $scop ...

The oncanplaythrough event is not functioning properly in Internet Explorer

I am facing an issue where the beep sound trigger upon receiving an API response works perfectly in Chrome and Firefox browsers, but unfortunately, it does not work in Internet Explorer. if ($scope.totalQueueList) { var audio = new Audio(); audio.s ...

Using a plugin to implement an AJAX submission feature on the WordPress WooCommerce cart page

Recently, I developed a plugin that displays a form on the shopping cart page. Upon submission, I send the data to a third-party server. jQuery.ajax({ type: 'POST', url: 'http://www.yoursitename.com/wp-content/plugin/my-ajax.php& ...

How to Retrieve URL Before Closing a jQuery Window Using window.open()?

Is it feasible to retrieve the URL of a window.open window after triggering a window.close event when the user clicks the close button? How can I obtain the last URL visited right before the window closes? ...

What are some alternative methods for updating content with ajax in ASP.Net web forms aside from using UpdatePanels?

In my experience with web UI development, I have gained a strong understanding of ASP.Net Web Forms over the course of four years. However, I have struggled to find an efficient way to update sections of a page using Ajax. I have tried various methods invo ...

Guide on implementing automatic callbacks with AJAX

I am facing an issue with my index page that has one input tag and one division. There is an ajax function that retrieves data from the server, but I am encountering a problem. When I enter a single letter, it returns 3 records. Then, if I add another lett ...

How can I stop a page from refreshing after a submission?

Currently, I am working on a PHP programming project that involves interacting with a database. I am facing an issue where upon submitting form data to be inserted into the database on the same page, if the page is reloaded, it shows an error. I have been ...

How does the indexing of Gmail and Facebook chat differ from iframes, ajax, and URL anchors?

Although I'm still a bit uncertain about how it all works (but that's not the main focus!), it seems like the majority of the content (almost all of it!) is within the iframe, while the chat window is located outside of it. Requests are most like ...