function for ajax response is received

How can I replace HTML code with the 'for from django' function using a jQuery AJAX call?

$.ajax({                                                                                                                           
    url: url,
    data: $('#FormSite').serialize(), 
    type: "POST",
    async:false,
    success: function(response) {
        $($("#Pic").first()).replaceWith($(response['Pic']));
        $("#HeaderWpis").text(response['h1']);
        $("#WpisChild").html("<div id='WpisChild'> {% for News in Messags %} <p>{{ News.title }}</p> </div>");
    },
    error: function(data)
    {
        alert('Bad connection');
        console.log(data);
    }

});

After trying this, I noticed that the {%for%} from the third div 'WpisChild' is displayed as text instead of being processed by the function. Can you explain why this is happening?

Answer №1

When accessing your views, the Django template language is processed, making it inaccessible to JQuery interpretation. Here are a couple of solutions:

  1. To utilize the Django template language in generating HTML, use the render() function in your views.py file. Create a new template containing the HTML segment and direct the AJAX call to a new view. Pass the Messages as context to the template and implement a {% for %} loop to work with it. The response will be the fully constructed HTML that can be appended to the desired div.
def get_messages(request):
    if request.method == 'POST':
        # Perform actions with the request, fetch messages

        context = {
            'Messages': messages
        }
        return render(request, 'message-template.html', context)
$("#WpisChild").append(response)
  1. Alternatively, embed the Messages data in your current response, iterate through the list, and append each one as an element to the div. This approach may be preferable if your response contains other data.
response['Messages'].forEach(function(news) {
    $("#WpisChild").append('<p>' + news.title + '</p>')
});

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

Utilizing Vue.js with Firestore: Retrieve information from Firestore without rendering any data on the screen

When attempting to display my data from Firestore, I encountered an issue where the data was retrieved successfully when hovering over the <td> tag but not actually displayed. Here is my file for fetching data from Firestore: <template> & ...

Clicking on a checkbox within an HTML table that incorporates handlebar and Express.js

My situation involves a HTML table within a form that is being populated with Handlebars. I need to be able to select certain rows in the table using checkboxes, and upon form submission through a POST request in an Express.js framework, I require the JSON ...

Storing Json data in a variable within Angular 2: a step-by-step guide

https://i.sstatic.net/2QjkJ.png Within the params.value object, there are 3 arrays containing names that I need to extract and store in a variable. I attempted to use a ForEach loop for this purpose, but encountered an issue. Can you spot what's wron ...

Form validation using jQuery and AJAX

I've implemented validation in my ResetPassword function and it seems to be working fine. However, I'm facing an issue where the ResetPassword function stops working once the validation is added. Can someone guide me on how to resolve this issue? ...

When utilizing AJAX, certain web pages may contain a querystring

Encountering an issue with ajax when using query strings. Data can be successfully sent when the page does not have any query string and Info.aspx/Save works perfectly fine. However, when I include query strings and post the same data, it results in a HTTP ...

The reason behind my unsuccessful attempt to utilize AJAX with the Google GeoChart API

Learning about JavaScript is exciting! I recently tried incorporating a Google Geochart to generate visual reports. The sample code looked like this: function drawRegionsMap() { var data = google.visualization.arrayToDataTable([ ['Country ...

Tips on adding line breaks after periods that are not at the end of a sentence in HTML text nodes with regular expressions

Looking to craft a regex that can identify all periods not enclosed in quotes and not followed by a '<'. This is for the purpose of converting text into ssml (Speech Synthesis Markup Language). The regex will be utilized to automatically inse ...

What is the best way to keep a button visible at all times and active without needing to be clicked?

<v-card :style="{ textAlign: 'left' }" class="basic-card pa-6" :class="{ 'small-padding': !$vuetify.breakpoint.xl }" elevation="0" flat :height="windowHeight - 104 + 'px&ap ...

Passing parameters from a div to a single page component in Vue.js: A complete guide

There is code that appears on multiple pages: <div id="contact-us" class="section md-padding bg-grey"> <div id="contact"></div> <script src="/dist/build.js"></script> </div> Included in main.js is: im ...

What is the best way to iterate over JSON data and organize the output based on the key value?

Let's say I want to filter through the JSON data below and only push the home_team_conference if it matches Southeastern. My goal is to organize the data by home_team_conference in order to display each array on different pages of my website. Currentl ...

Error: Conversion of "2018-01-01-12:12:12:123456" to a date is not possible for the 'DatePipe' filter

<td>{{suite.testSuiteAttributes && suite.testSuiteAttributes.modifiedTimestamp | date: 'yyyy-MM-dd' }} </td> I am trying to display the date in the "05-Feb-2018 11:00:00 PM CST" CST format, but I keep getting an ...

Using nodeJS's util module to format and pass an array

I've been using util.format to format strings like this: util.format('My name is %s %s', ['John', 'Smith']); However, the second parameter being an array ['John', 'Smith'] is causing issues because m ...

Jquery error - parser issue - JSON input unexpectedly terminated

I am facing an issue with retrieving information from my database and displaying it in a table using JQuery. Previously, I was able to do this successfully with the same code, but now it seems to be malfunctioning. Despite researching various resources for ...

How to create expandable nodes with lazy-loaded children in Dynatree?

I have successfully implemented a tree navigation menu using Dynatree (). The tree consists of four levels: company, group, user, and computer. Each object within the tree is selectable, opening a page displaying the properties of that specific object. How ...

Integration of Django Tastypie with Angular for secure user authentication

I'm currently facing an issue where I cannot establish a connection to the Django server. Upon checking the browser console, I noticed the following error message: [![console error][1]][1] My setup involves using Tastypie along with a UserResource c ...

Dealing with Sideways Overflow Using slideDown() and slideUp()

Attempting to use slideUp() and slideDown() for an animated reveal of page elements, I encountered difficulty when dealing with a relatively positioned icon placed outside the element. During these animations, overflow is set to hidden, resulting in my ico ...

Displaying feedback messages and redirecting in Flask may result in the response being visible in the developer tools, but

Just starting out with Flask and encountering an issue. I am trying to determine if a response is empty, and if it is, display a message. The problem lies in the fact that even though the redirect works and the subsequent GET request returns the correct HT ...

Discover the following `<td>` identifier through the act of clicking on a separate `<td>` element

I have a few td's with specific ids: <td id="first">first</td> <td id="second">second</td> <td id="third">third</td> <td id="fourth">fourth</td> Whenever I click on one of the td elements, I want to re ...

Accessing a variable outside of the component constructor will result in the variable being

Currently, I am tackling a project that involves React and Electron. However, I have encountered an error that is causing some confusion. The issue revolves around a component with a constructor that receives props in the form of two variables. This constr ...

The spreading of personalized events

I am expecting my CustomEvent to be propagated from the document to all the DOM elements. However, for some unknown reason, it is not happening. Can you point out what mistake I might be making? <html> <script> function onLoad() { var myDi ...