Updating the button's appearance after submission using jQuery and Django

I have implemented an ajax "follow" button on my website. Currently, the button's attribute disabled changes to "disabled" after submission. However, I would like to modify the button from "follow" to "unfollow" upon submission, similar to how it works on Twitter. How can I achieve this? I attempted to change the button's attribute "form" to submit another form using the following code:

success:function(){
                $button.attr('form','unfollow');

Unfortunately, this approach did not work as intended.

Below is a snippet of the template file event.html:

{% if user in event.users.all %}
            <form id="unfollow">
            {% csrf_token %}
            <input type="hidden" value="{{ event.id }}" name="remove">
            <button type="submit" class="btn btn-warning btn-block">{% trans "Unfollow"%}</button>
            </form>
    {% else %}
            <form id="follow">
            {% csrf_token %}
            <input type="hidden" value="{{ event.id }}" name="add">
            <button type="submit" class="btn btn-primary btn-block">{% trans "Follow"%}</button>
            </form>
    {% endif %}

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
    <script type="text/javascript">

    $(document).on('submit','#unfollow', function(e){
        var $button = $(this).find('button');
        e.preventDefault();
        $.ajax({
            url:'/event/{{ event.id }}/',
            data: "remove={{ event.id }}",
            success:function(){
                $button.attr('disabled', 'disabled').text('{% trans "Unfollowed" %}');
            }
        })
    });

    $(document).on('submit','#follow', function(e){
        var $button = $(this).find('button');
        e.preventDefault();
        $.ajax({
            url:'/event/{{ event.id }}/',
            data: "add={{ event.id }}",
            success:function(){
                 $button.attr('disabled', 'disabled').text('{% trans "Followed" %}');
            }
        })
    });

</script>

views.py

user = request.user
if request.GET.get('add'):
    event.users.add(user)
    event.save()
if request.GET.get('remove'):
    event.users.remove(user)
    event.save()

Answer №1

One issue that stands out is the existence of two endpoints (follow / unfollow) that essentially perform similar actions.

To streamline this process, consider consolidating these into a single endpoint that toggles the status (between follow and unfollow). This way, you only need to send the event ID using a unified form.

Although I'm not well-versed in Python, the code should resemble something like this:

views.py

...

template.html

...

JS

...

Check out this jsFiddle for a visual representation: https://jsfiddle.net/1u39dhjh/

Please ensure that you are correctly handling form submission via Ajax with Django, as the csrf token needs to be included.

I hope this guidance proves useful to you.

Answer №2

To implement this functionality, you can include both forms in your HTML and use CSS to hide or show them based on user action:

<form id="unfollow" {% if user not in event.users.all %}style="display:none;"{% endif %}>
    {% csrf_token %}
    <input type="hidden" value="{{ event.id }}" name="remove">
    <button type="submit" class="btn btn-warning btn-block">{% trans "Unfollow"%}</button>
</form>

<form id="follow"% if user in event.users.all %}style="display:none;"{% endif %>
    {% csrf_token %}
    <input type="hidden" value="{{ event.id }}" name="add">
    <button type="submit" class="btn btn-primary btn-block">{% trans "Follow"%}</button>
</form>

Update your JavaScript code as follows:

success: function() {  // Hide follow form and display unfollow form
    $followForm.hide();
    $unfollowForm.show();
}

success: function() {  // Hide unfollow form and display follow form
    $unfollowForm.hide();
    $followForm.show();
}

You can also utilize a state variable to determine which form should be hidden or shown.

NOTE: It is recommended to use POST method instead of the GET method for actions that modify data.

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

Server unable to process header location following JS redirect, even though it functions correctly on localhost

I have been developing a login system that directs users to specific URLs based on their user type and activation status. Below is the code snippet: $.post( './assets/tasks/process-login.php', { email:email, ...

Tips for successfully retrieving a variable from a function triggered by onreadystatechange=function()

Combining the ajax technique with php, I'm looking to extract the return variable from the function called by onreadystatechange. A java function triggers a call to a php script upon submission, which then validates certain data in the database and r ...

The Ajax GIF Loader is not functioning in the latest versions of Internet Explorer and Firefox, but it is running smoothly in

The animated GIF loader functions correctly in the latest version of Chrome, but does not animate when viewed in IE and Firefox. Below is the code snippet: $("#DIALOG").dialog({ buttons : { "Yes" : function() { ...

Make sure to refresh the model using an Ajax request in Spring MVC

I have a page where I use AJAX to insert data into my database. On that same page, I display a table of records that are inserted. Each time I add a new record, I want to update the content of the table. Here is what I have implemented: @RequestMapping(va ...

Extract the text and value from an asp.net treeview by utilizing jQuery or JavaScript

On my website, I am using a TreeView controller. I have disabled node selection by setting SelectAction = TreeNodeSelectAction.None as I have the checkbox option enabled. However, this causes an error when trying to access the .href property of the node. T ...

Using jQuery to dynamically update the content of a modal's body

I have a pair of buttons (Modal 1 & Modal 2) on my website. <!DOCTYPE html> <html lang="en"> <head> <title>Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=d ...

Tips for sending a JavaScript variable through an AJAX URL

I currently have a variable defined like this: var myip; I need to include this variable in the following URL: $.ajax('http://api.ipstack.com/**[myip]**?access_key=mykey') Manually replacing [myip] with my IP address works fine, but I am loo ...

A guide to activating automatic filling of usernames and passwords in web browsers

On my login page, I aim to make the user experience seamless by automatically filling in the username and password fields once a user has logged in for the first time. This way, when they return to the login page, all they have to do is click the login but ...

Manually adding or removing rows in a DataTable

I've been racking my brain over this issue since yesterday and nothing seems to be working. Here's the problem: I have a table that utilizes DataTables (datatables.net). It needs to be cleared of all rows programmatically and then new rows added ...

How can I make an absolutely positioned div slide down from a specific area on the page using jQuery's slideDown() function?

I have a website project in progress where the main image on the homepage is of a house with windows and a door. The idea is that when a user clicks on a window, a <div> should appear with some text. Similarly, clicking on the door should trigger a & ...

Having trouble with your jQuery onclick function not triggering?

Clicking a specific 'link' will reveal a div containing content. Once clicked, the 'Open' button transforms into a 'Close' button with closing capabilities. jQuery Code $(document).ready(function () { $('.open_us ...

Tips for obtaining the retrieved URL from an ajax call

How can I extract only the returned URL from an ajax request? I have tried implementing it like this: $.ajax({ type: "GET", dataType : "jsonp", async: false, url: $('#F ...

Unable to save Ajax data in session array

Currently, I am developing a cart system using jquery, ajax, and php. The issue I am facing is that the text within the HTML elements is not being added to the session array. Below is the ajax code I am using: $(document).ready(function(){ $("#car ...

What's the reason behind the error message "local variable 'text' referenced before assignment" popping up on my screen?

I am attempting to develop a sharing feature using Python and Django, but when I try to execute the "share" function, an error is returned. Below is the code I am working with: views.py from django.shortcuts import render from basicapp.forms import U ...

Is there a way to trigger a function within the submit handler with jQuery validation?

I've been attempting to trigger an ajax function once the form is validated, but I'm running into some issues. The jQuery on-submit method below is working perfectly for me. $('#promotionAdd').on('submit',(function(e) { ...

Using AJAX to dynamically update content via HTTP requests

Why do I keep seeing "loading..." instead of the content from data.php? xmlhttp = new XMLHttpRequest(); function fetchData () { xmlhttp.onreadystatechange = function () { if(xmlhttp.readyState = 4 && xmlhttp.status == 20 ...

Trouble altering an attribute using jquery

Hey there, I'm struggling with changing the attribute for an id and can't quite pinpoint where I'm going wrong. It's not making things easier that I'm pretty new to this whole thing as well. I've created a function to ensure ...

Transfer information from PHP to JavaScript across distinct files

In my website, I have several files including login.php, main.php, functions_js.js and functions_php.php. The login.php file retrieves two variables that I need to pass to the functions_php.php file via AJAX. In functions_php.php, I execute a SELECT query ...

When using ajax, you will receive the source code of the page, rather

After searching everywhere, I have only found solutions involving jquery. However, my issue does not involve jquery at all. To solve the problem, I send an ajax string to a php file. The php file processes the data and generates a message string that is ...

Why am I receiving an error message stating "undefined is not a function" when trying

I am attempting to create a popover using the Angular UI pop over feature. I have loaded my HTML and compiled it, but when I run my program and click on the star icon (where I display the popover), I receive an error stating that 'undefined is not a f ...