Utilizing Ajax to handle and interpret a JSON HttpResponse

After sending an HttpResponse from views.py to an HTML page, I encountered an issue where only the JSON object is displayed instead of the expected details in the HTML format.

The current appearance of the page after the request: https://i.sstatic.net/yFeUf.png

This is how the data should ideally be displayed: https://i.sstatic.net/ZZuHI.png

views.py

def tracker(request):
    if request.method == "POST":
        oid = request.POST.get('oid', '')
        email = request.POST.get('email', '')
        try:
            order = Orders.objects.filter(order_id=oid, email=email)
            if len(order) > 0:
                update = OrderUpdate.objects.filter(order_id=oid)
                updates = []
                for item in update:
                    updates.append({'text': item.update_desc, 'time':item.timestamp})
                    response = json.dumps(updates, default=str)
                return HttpResponse(response)
            else:
                return HttpResponse({})
        except Exception as e:
            return HttpResponse({})

    return render(request, 'shop/tracker.html')

tracker.html

{% include 'shop/basic.html' %}
{% block body %}
<div class="container">
    <div class="col my-4">
        <h2>My Awesome Cart Tracker - Enter your Order ID and Email address to track your order</h2>
        <form method="POST" action="#" id="trackerForm">
            {% csrf_token %}
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for="Oid">Order Id</label>
                    <input type="text" class="form-control" id="oid" name="oid" required="">
                </div>
                <div class="form-group col-md-6">
                    <label for="inputEmail4">Email</label>
                    <input type="email" class="form-control" id="inputEmail" name="email" required="">
                </div>
            </div>
            <button type="submit" class="btn btn-primary">Track Order</button>
        </form>
    </div>
    <div class="col my-4">
        <h2>Your Order Status</h2>
        <div id="items" class="my-4">
            <ul class="list-group my-4" id="items">
                Enter your order ID and Email and click Track Order to find details about your order!
            </ul>
        </div>
    </div>
    {% endblock %}

    {% block js %}
    <script>
        $('#trackerForm').submit(function (event) {
            $('#items').empty();
            var formData = {
                'orderId': $('input[name=oid]').val(),
                'email': $('input[name=email]').val(),
                'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
            }
            $.ajax({
                type: 'POST',
                url: '/shop/tracker/',
                data: formData,
                encode: true
            })
                .done(function (data) {
                    updates = JSON.parse(data);
                    if (updates.length > 0 & updates != {}) {
                        for (i = 0; i < updates.length; i++) {
                            let text = updates[i]['text'];
                            let time = updates[i]['time'];
                            mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
                    ${text}
                    <span class="badge badge-primary badge-pill">${time}</span>
                </li>`
                            $('#items').append(mystr);
                        }
                    }
                    else {
                        mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
                    Sorry, we are not able to fetch this order ID and email. Kindly recheck the Order ID and email.</li>`
                        $('#items').append(mystr);
                    }

                });
            event.preventDefault();
        });
    </script>
    {% endblock %}

Answer №1

Make sure to include event.preventDefault() before sending an Ajax request.

It is important to prevent the default behavior of the submit button by calling event.preventDefault() prior to executing the Ajax request. Otherwise, the DOM may have already been modified by the time the httpresponse is returned, causing unexpected changes.

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

Using selenium to create a brief pop-up message that appears for a few seconds

I have a Selenium script in Java that opens a Google web page and then closes the browser. Upon closing the browser, I want a pop-up message to appear briefly with the text "Code executed" before fading away after a few seconds. I know that I can achieve t ...

How come my date computed property does not update reactively when changes occur?

I have a Date object in my data, and I need to convert the date into a string for a date picker component in Vuetify. The initial date is being read and displayed correctly. I am able to set the date as well - when I set a code breakpoint, I can see the ...

A revolutionary chat platform combining HTML, PHP, AJAX, JavaScript, and MySQL technologies

In my search for a straightforward chat application example online, I have come across many options using PHP (index.php) with MySQL and AJAX. However, this is not what I am looking for. I am specifically in need of a simple Peer to Peer and Peer to Group ...

The use of anonymous arrow functions results in Fast Refresh not maintaining local component state

I am facing an issue with the code in my pages/index.js file: import React from 'react'; import dynamic from 'next/dynamic'; const TVChartContainer = dynamic( () => import('../components/TVChartContainer').then ...

What exactly do `dispatch` and `commit` represent in vuex?

Recently, I came across a Typescript project in Vue.js with a Vuex store that had the following code: async getUserProfile ({ dispatch, commit }: any) {} I found working with any cumbersome as it doesn't provide helpful autocomplete features in the ...

Preventing users from using alt+tab on an IE8 aspx web page

I need help with disabling the alt+tab function in my IE8 web browser for a page that displays a modal dialogue. Can anyone assist me with this issue? ...

VueJs Ellipsis Filter: Enhance Your Texts with

Using Vue.JS, I am dynamically injecting text content into a DOM element. <article>{{ movie.summary }}</article> My goal is to implement an auto-ellipsis filter. Essentially, the code would look like this: <article>{{ movie.summary | e ...

Ways to inform the user of updated information, prompting them to refresh their page

Currently, I am developing a news app that retrieves data directly from the server in JSON format. After parsing it, the information is displayed on the views. My goal is to notify users when new data becomes available and prompt them to refresh manually i ...

"Troubleshooting a 400 Bad Request Error in Node.js and Express for a

It seems like I must be making a silly mistake, because this should be a simple task. All I want to do is send a POST request in an Express route. This is my app.js: var express = require('express'); var path = require('path'); var f ...

Tips for resolving the 'TemplateDoesNotExist' issue in Django 4.2 during server execution

TemplateDoesNotExist at / home.html Request Method: GET Request URL: http://127.0.0.1:5555/ Django Version: 4.2.1 Exception Type: TemplateDoesNotExist Exception Value: home.html Exception Location: C:\Users\soumy\AppData\Local&bs ...

Deciphering JSON in Golang to form a slice containing a string and a float64 value

I'm currently working on querying a database that is located on a server. The issue arises when I attempt to decode the JSON data into a 2D slice, as one element is a string while the other is a float64. To tackle this problem, I initially tried modi ...

Scroll indefinitely, obliterate and regenerate elements as you scroll

I have a unique issue that I need advice on from experts in this field. On my website, I have a Tree with infinite scroll functionality. The tree's image is iterative and the number of iterations depends on the data source provided. The data source ...

Execute a function (with arguments) within a v-for loop in Vue.js

Currently, I am attempting to create a select element using Vue.js and Material Design that has 2 levels: categories and items. Each category can contain multiple items which may be selected or not. <md-select v-if="categories.length > 0" name="cate ...

Tips for incrementing or decrementing numbers to the right of the decimal in ReactJS

Currently working with react js and encountering an issue. I have an input field equipped with increment and decrement buttons situated on the right side. The problem arises when I try to increment the field, as it's actually the number on the right s ...

Locate blank input fields within a group - using jQuery

In my quest to identify empty input elements such as textboxes, select dropdowns, and list items within a jQuery result set denoted as (requiredfields) - $requiredFields = $(".f-form-required.f-form-field").filter(function(){ if($(':input:not([typ ...

What could be the reason for the malfunction of my AJAX post request?

I am facing an issue with my AJAX method in Django - it doesn't seem to be working properly. The problem is, I can't pinpoint where the issue lies because there are no errors showing up in the Django debug log, and it returns a 200 status code. ...

Conceal the URL and any parameters upon successful completion of AJAX request

In my ajax js code, the solonreport.jsp file returns a URL link that connects to a local report server and generates an Excel report. However, when using this link with the window.open(json.url) function, the link and parameters are visible to the user. ...

Inconsistency in displaying updated values in AngularJS directives

I am facing an issue where I need to postpone the compilation of a child directive until a promise in the parent directive's prelink function is resolved and a value (CONFIG) is updated. Within the Parent's preLink: somePromise.then(functio ...

I successfully managed to ensure that the splash screen is only displayed upon the initial page load. However, I am now encountering an issue where it fails to load again after I close the page. Is there any possible solution

After successfully implementing a splash screen that only plays once on page load, I encountered an issue. When I close the tab and revisit the page, the splash screen no longer plays. Is there a way to fix this problem? Perhaps by setting a time limit for ...

Tips for dynamically changing the number of visible ListItems in React using a single method

I recently stumbled upon the perfect solution at this link using material-ui. The chapter on "Nested list items" caught my attention, as it only has one nested item with a method for expanding more or less. In my sidebar, I have two nested items that both ...