Update Django 3.2 to use AJAX to fetch and display data instead of rendering HTML web pages

I successfully implemented ajax on my website to update the content without refreshing the page. However, I am facing an issue where I can't replace the old content with the new one that is returned. When I use console.log(data), I can see the new HTML but I'm struggling to display it to the user.

Below is the Ajax code for submitting the form:

<script>
$(function() {
    $("#show_type").submit(function(event) {
        // Prevent form from submitting normally
        event.preventDefault();
        let friendForm = $(this);
        // Send the data using post
        let posting = $.post(friendForm.attr('action'), friendForm.serialize());
        // if success:
        posting.done(function(data) {
            console.log(data); // New HTML
            window.alert("Action successful");
            // Perform success actions, such as changing the submit button text to 'Friend Added'
        });
        // if failure:
        posting.fail(function(data) {
            window.alert("Action failed");
            // Alert the user about any 4xx or 5xx response error
        });
    });
});
</script>

The Google Chrome console log shows the new HTML that I want to display on the browser, but I'm unsure how to do it:

<div class="grid-container">
         
         <div class="grid-item" start_at="10 août 2021 12:46" end_at="10 août 2021 17:45">
            <span class="device-title">Device nostart [ID]: C23</span>
            <div class="device-info">
               <span class="left-text-icon map">Location: HIDE</span>
               <span class="left-text-icon start">Start: 10 août 2021 12:46</span>
               <span class="left-text-icon end">End: 10 août 2021 17:45</span>
               <span class="left-text-icon chief-go">Chief GO: cdcd chieffunc</span>
               <span class="left-text-icon dchief-go">Deputy Chief GO: did azda</span>
               <span class="left-text-icon dso">DSO: Souris azd</span>
               <div class="resume">
                   <div class="resume title">Unit Summary</div>
                   <div class="resume content left-resume-icon hurt">Injured 0</div>
                   <div class="resume content left-resume-icon arrest">Arrests: 0</div>
                   <div class="resume content left-resume-icon grenade">Grenades fired: 0</div>
                   <div class="resume content left-resume-icon water">Liters of water used: 0</div>
                   <div class="resume content">UUID </div>
               </div>
            </div>
        <form action="/home/delete_device/9/" method="post">
            <input type="hidden" name="csrfmiddlewaretoken" value="HIDE">
            <input type="submit" value="Delete device">
         </form>
      </div>
      
</div>

Your assistance is greatly appreciated!

Answer №1

I discovered the solution:

reference: https://api.jquery.com/replacewith/

$("div.grid-container").replaceWith(data);

this code replaces the <div class="grid-container"> with the HTML content stored in the variable "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

Displaying data on View is not working after navigation

I'm facing an issue where the data is not displaying on the view after routing, even though it appears in the console. Surprisingly, if I don't change the view, the data shows up. Additionally, if I call the service directly from the view, I can ...

What steps do I need to take to deploy my React app onto a server?

I recently completed creating my first website with React and now I want to upload it to my server (HostGator). Can anyone guide me on how to do that? Thank you. ...

Improving efficiency of basic image carousel in Angular 8

In my Angular 8 app, I am developing a basic carousel without relying on external libraries like jQuery or NgB. Instead, I opted to use pure JS for the task. However, the code seems quite cumbersome and I believe there must be a more efficient way to achie ...

Sharing images on a web app using Express and MongoDB

My objective is to develop a portfolio-style web application that allows administrators to upload images for other users to view. I am considering using Express and MongoDB for this project. I am uncertain about the best approach to accomplish this. Some ...

Is it possible to attach a PDF file using just the PDF URL?

My current project involves an ionic application that performs calculations based on user inputs. Once the calculations are complete, the results are converted into a PDF using the generatePDF API call. Additionally, there is a requirement to email the gen ...

Issue encountered while attempting to send a direct message to a user that has been mentioned

Attempting to create a reminder command in discord.js with two arguments: the message and the mentioned user to remind but encountering an error. Code snippet: client.on('message', (message) => { const { content, guild, channel, author } = m ...

Is there a way to verify if the overflow of an element with a width of 100% has occurred?

Here is the structure I am working with: <div class="card"> <div class="container"> <slot /> </div> </div> The Card element has a fixed width of 33rem. The container within it spans 100% of ...

Sending Data Between Web Applications in JavaScript

Currently developing a take-away application using AppLab, which uses JavaScript. Due to the limitations of modifying HTML code in AppLab, I had to utilize an external web app for the checkout process (unable to integrate PayPal buttons in AppLab). When th ...

How can I eliminate the extra '/' in all links when building with webpack and vue?

I have a question that might seem silly to some, but it's really frustrating me. I am currently working on a project using Vue with vue-cli. this is the webpack build result <!DOCTYPE html> <html> <head> <meta charset=utf- ...

What is the best way to efficiently test modifications while building a Chrome Extension with ReactJS?

When testing my chrome extension using npm run, I encountered an error stating 'chrome' is undefined. To interact with their API, I utilize chrome.storage.sync to store user data, chrome.runtime.lastError for runtime checks, and chrome.tabs.quer ...

Expand Elements to occupy entire width

My CSS skills are still in the early stages. I haven't delved too deeply into it. I have a query regarding how to achieve full width for an element. I've included my code below, but the basic approach I tried using 'width: 100%' didn&a ...

Tips for locating the ID of an object in an array when only one attribute in the "child" array is known

Seeking assistance in creating a JavaScript function that efficiently determines the id of the "parent" object based on the code of a "child" object from the dataArray. For example: getIdParent("240#code") -> should return "1" [ { id: 0, ...

What could be causing the issue with insertMany not working when using Mongoose with transactions?

I'm having trouble inserting data using the inertMany method. Despite my efforts, I can't seem to successfully insert the data. I am utilizing mongoose session to handle any errors that may arise and rollback changes if needed. Check out this li ...

Creating a worldwide object in JavaScript

I am trying to create a global object in JavaScript. Below is an example code snippet: function main() { window.example { sky: "clear", money: "green", dollars: 3000 } } However, I am unable to access the object outside th ...

Retrieve the previous value of the selection change with the Mat Select function

In my current project, I have a form with a mat-select dropdown. Whenever the user makes a selection, a dialog pops up to confirm the choice. However, I am facing an issue: The selectionChange() event is triggered when the value changes and provides the n ...

What is preventing the console from identifying the ID?

I'm working on a project that involves displaying the id, latitude, and longitude in the console. The goal is to save this information in an array and then store it in a mysql database using the Google Maps Javascript API. Below is the code: <scr ...

The Angular/Bootstrap Modal is not functioning properly: TypeError occurs due to v2.deleteModalProject not being recognized as a function and

My main objective is to allow users to call the modal multiple times for content deletion. However, I encountered issues when the modal was triggered a second time without reloading the page. I am currently working with Angular version 1.5.6 After spendi ...

How can I generate a fresh window/frame within my Javascript canvas?

Is there a way to open a new frame or window within the canvas using JavaScript? I am working on a game project where I want to implement a feature that displays additional information on a menu screen when a button is pressed. Currently, I have managed to ...

Moving the HTML object back can be achieved by translating several times on the X axis followed by translating on the Y axis

Before I proceed with my inquiry, please keep in mind the following: I have no intention of using a game engine. This game is being created using HTML, CSS, and JavaScript. The controls are set to three arrow keys, where clicking on one should move in th ...

Navigating through JSON data to retrieve specific values and executing repetitive actions

When the form is submitted, I am making an AJAX request to PHP code and this is the response I receive. var data = { "empty":{ "game_sais_no":"Season cannot contain empty value", "game_sc_no":"Category cannot contain empty value", ...