What could be causing the AJAX in Django not to work with this particular second form?

I encountered some strange issues with Ajax while developing an application in Django. My website has 4 forms that need to be processed using Ajax, and two of them are working perfectly fine. However, the other 2 forms seem to have no idea about Ajax. Let's take a look at the working and non-working forms.

views.py

Working Form View

def login_user(request):
    form = LoginForm(request.POST)
    context = { 'form': form, }

    if request.method == 'POST' and form.is_valid():
        username = form.cleaned_data['user_login']
        password = form.cleaned_data['user_password']
        user = authenticate(username=username, password=password)
        response_data = {}
        if user and user.is_active:
            login(request, user)
            response_data['result'] = 'Ok'
        else:
            response_data['result'] = 'Bad'
        return HttpResponse(json.dumps(response_data))  
    else:
        return redirect('index') 

Non-Working Form View

 def add_new_station(request, add_station_slug):
        form = AddStationForm(request.POST)
        myuser = get_object_or_404(User, id=request.user.id)
        print(request.user)
        if request.method == 'POST' and form.is_valid():
            response_data = {}
            UserStation.objects.create(
                station=Station.objects.get(slug=add_station_slug),
                impressions=form.cleaned_data['impressions'],
                list=UserStationsList.objects.get(user=myuser)
                response_data['result'] = 'Ok'
            )
            return HttpResponse(json.dumps(response_data)) 
        else:
           return redirect('index')

urls.py

    urlpatterns = [
        path('', index, name='index'),
        path("add-in-list/<str:add_station_slug>/", add_new_station, name='new_station'),
        path('login/', login_user, name='login_action'),
        ...
]

HTML

HTML for Working Form

<form id="login_form" action="{% url 'login_action' %}" method="post">                                       
   {% csrf_token %}                                          
   {{ formlogin }}                                   
    <div class="text-center">
        <button type="submit" class="btn btn-dark mt-2">Entry</button> 
    </div>                                   
</form>

HTML for Non-Working Form

<form id="add_station_form" action="{% url 'new_station' choice_station.slug %}" method="post">
     {% csrf_token %}
     {{ formaddstaion }}
     <div class="text-center">
          <button type="submit" class="btn btn-outline-success mt-2">I visited this  station</button>
     </div>
 </form>

main.js

Script for Working Form

$('#login_form').submit(function() {
    $.ajax({ 
        data: $(this).serialize(), 
        type: $(this).attr('method'), 
        url: $(this).attr('action'), 
        success: function(response) {
            data = JSON.parse(response)
            if (data['result'] === "Ok"){
              $('.login-message').hide()
              location.reload()
            }
            else{
              $('.login-message').show(100).html('wrong data')
            }
        }
    });
    return false;
});

Script for Non-Working Form

$('#add_station_form').submit(function() {
      $.ajax({ 
          type: $(this).attr('method'), 
          url: $(this).attr('action'), 
          success: function(response) { 
              data = JSON.parse(response)
              alert('data') // try check, but ajax don't reach here
          }
      });
      return false;
    }); 

The first case functions perfectly, whereas in the second case, Ajax doesn't seem to initiate at all (it simply redirects me to the page with HttpResponse). What could be causing this issue?

Answer №1

When sending a POST request to a Django view using AJAX, it's important to note that POST requests do not contain parameters in the URL. To overcome this, you should remove the parameter from the URL and make some adjustments as outlined below:

To remove the parameter from your URL, add a hidden input field to your form instead. This hidden input field will hold the parameter value.

<form id="add_station_form" action="{% url 'new_station' %}" method="post">
   {% csrf_token %}
   {{ formaddstaion }}
  <input type="hidden" name="add_station_slug" value="{{choice_station.slug}}" readonly>
  <div class="text-center">
    <button type="submit" class="btn btn-outline-success mt-2">
         I visited this  station
    </button>
  </div>
</form>

For the AJAX part, follow the instructions provided by @Borut. Pass the data to your AJAX request accordingly:

$.ajax({ 
   type: $(this).attr('method'), 
   url: $(this).attr('action'), 
   data: $(this).serialize(),
   success: function(data) { alert(data.response); }
});

In your urls.py file, ensure that the parameter is removed:

urlpatterns = [
  ...
  path("add-in-list/", add_new_station, name='new_station'),
  ...
]    

Lastly, in your views, extract the parameter and utilize it as needed:

from django.http import JsonResponse 
# From Django 1.7 onward, prefer using JsonResponse over HttpResponse

def add_new_station(request):
   response_data = {'response': 'Something went wrong!'}
   form = AddStationForm(request.POST)
   myuser = get_object_or_404(User, id=request.user.id)
   
   if request.method == 'POST' and form.is_valid():            
      slug = request.POST.get('add_station_slug')
      UserStation.objects.create(
        station=Station.objects.get(slug=slug),
        impressions=form.cleaned_data['impressions'],
        list=UserStationsList.objects.get(user=myuser)                
      )
      
   response_data['response'] = 'UserStation Created Successfully!'
   return JsonResponse(response_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

Updating a JavaScript global variable within a click event function: A quick guide

I am currently using Javascript and jQuery to retrieve the mouse coordinates of a click event for use in other Javascript functions. The issue I am facing is that global variables set within an event function do not update outside the function, unlike glob ...

Navigating the landscape of European law and online payment regulations can be complex, especially when it

Currently, I am in the process of developing a website that integrates Stripe payments. Since it is based in Europe, I will be required to implement SCA 3D Secure authentication. According to the documentation provided by Stripe, it is recommended to handl ...

Stop prior requests upon clicking

My current task involves managing a list of tables. <table id="<%#DataBinder.Eval(Container.DataItem, "Certificate")%>" class="tbl_evenSearchResultRow" onmouseover="this.className='ResultGridRowSeleted'" onmouseout="this.className=&apos ...

Utilizing Page Objects to select dropdown list items in JavaScript for Protractor testing

I'm struggling with a particular issue during my testing process. The task requires selecting an item from a list as part of a form to create a new user. However, the test does not select an item from the list even though Protractor does not report an ...

Guide for accessing and interpreting a random folder arrangement using JavaScript located alongside index.html

I am currently developing a testing reporting tool that organizes images into folders, resulting in a structure similar to this: root/ /counter/ img1.png img2.png /alarm/ img3.png The names of the folders like counter and alarm are not f ...

Organizing dynamic JSON keys with the help of map and reduce functions in JavaScript

Is there a way to group Dynamic Object keys of a JSON file? I want the object values for each key to be grouped accordingly. I attempted to use map and reduce functions to achieve this grouping, but the results did not turn out as I had expected. Below i ...

Tips for sending an object to a specialized child component in ReactJS with Typescript

Purpose I am trying to retrieve data in the root component of my app using useEffect() (and then set it to state) and then pass that state to a custom component. I have successfully accomplished this with JavaScript but seem to be encountering issues when ...

Tips for converting a raw SQL query to Knex syntax

Recently delving into the world of development, I've come across knex for the first time. Issue: I have a raw SQL query that is functioning correctly. Now, I'm attempting to utilize knex for this query. To better understand how things operate, I ...

Turning variables into a JSON string using the JSON stringify method

Currently, I am working with JSON stringify and here is the code snippet: var myObject = {}; for(var i=0; i < arr.length; i++){ myObject[i]=[]; //myObject[i].push('image:'+arr[i].id); myObject[i].push('nick:&a ...

Is there a way to create an interactive animation where an image responds to the movement of the mouse, but does not directly follow it

Looking to create an interactive experience where images on the webpage move in response to mouse movement. For example, if an image is at coordinates (0,0) and the mouse moves from (32,45) to (32,47), the image should shift vertically by 2 pixels. I atte ...

Expand the <div> by clicking on it, then hover away to return it to its normal size

One interesting feature I have on my website is a <div> that expands when clicked, and returns to normal size with another click. However, I am looking for something a bit different... What I want is for the <div> (with the class name .topHead ...

hover over the picture with your cursor

Struggling with jquery and css, could use some assistance :) Check out my html code below: <html> <head> //myscripts <script> $(document).ready(function(){ $(".cover").hover(function(){ //the function i need to write } ...

The function called Nuxt: n2 is not defined

When using Nuxt 3, I encountered a TypeError that looks like the following: Uncaught TypeError: n2 is not a function My issue revolves around a button that triggers the function toggleSelectRow with a @click.prevent directive. The function in question is ...

Learn how to implement a conditional class binding in Vue 3, and discover how to apply additional classes when a specific condition is met

As a newcomer to Vue.js 3, I am wondering how to implement a conditional class binding in Vue 3. Specifically, I would like to achieve the following logic: if router.path != '/', then add the class 'nav-bar-two'; otherwise, do not apply ...

Grab a parameter from the URL and insert it into an element before smoothly scrolling down to that

On a button, I have a URL that looks like this: www.mywebsite.com/infopage?scrollTo=section-header&#tab3 After clicking the button, it takes me to the URL above and opens up the tab labeled tab3, just as expected. However, I would like it to direct m ...

Is it not the case that using spread syntax does not make a reference to the original array?

I am currently facing an issue with my React application. I have two Object arrays in my state, one called names and the other called shuffledNames. I am attempting to create a copy of the names array and shuffle it into the shuffledNames array. However, w ...

How do I retrieve data for every individual row in the table using a basic Ajax Jquery script?

I'm currently experimenting with a basic ajax>php>mysql tutorial found at However, I am facing an issue where I can only retrieve information from the first row of my table structured like this: -------------- | id | name| -------------- | 1 ...

Utilize HTML5 and JavaScript to calculate the velocity of a device by employing devicemotion and device

Can device speed in km/h be calculated using the devicemotion/deviceorientation HTML5 API? I am interested in determining whether a user is walking, running, or stationary without relying on the geolocation API, which may not be accurate indoors. ...

Tips for extracting only a portion of the JavaScript timestamp

I have a JavaScript timestamp that reads Tue Sep 30 2014 12:02:50 GMT-0400 (EDT). When I use the .getTime() method, I get 1412092970.768 Typically, this timestamp represents a specific time of today. My question is whether it's possible to extract o ...

Issue with Django and SQL Server: Error occurs when charfield exceeds 10 characters

Currently, I am using Django 1.2.3 along with django-pyodbc. Encountering an issue when trying to add a user with a username longer than 10 characters: The data types nvarchar and ntext are causing compatibility issues in the equal to operator Adding a ...