Fetching a Django view using an AJAX call and extracting the task_id from a Celery task

I have been facing a challenge trying to display data from a celery task in a separate window. My expertise in JavaScript and AJAX is limited, which is where I am encountering issues. Once a view is executed, the celery task commences and the subsequent HTML page (success.html) is displayed:

success.html

{% block content %}
  <body>
    {% if task_id %}
      <h1>task_id has been called: {{ task_id }}</h1>

    <script src="{% static 'MyAPP/bootstrap/js/task_output_retrieval.js' %}"></script>
    <script type='text/javascript'> task_state("{{ task_id }}"); </script>

    <script src="{% static 'MyAPP/bootstrap/js/update-hello-user.js' %}"></script>
    <script type='text/javascript'> second(); </script>

      <h1> END </h1>

    {% endif %}
  </body>
{% endblock content %}

Although I can confirm that the JavaScript is being invoked as a new window appears, I'm now sharing the contents of my .js file:

task_output_retrieval.js

function task_state (task_id) {
    var taskID = task_id; 
    var newWin = window.open('', 'new window', 'width=200, height=100');

    $.ajax({
            url: '{% url validate_task_state %}', 
            data: {'taskID':taskID},
            method: 'POST',
            dataType : "json",
            success: function(data){
                $(newWin.document.body).html(data);
                newWin.document.write(data);
                newWin.document.close();
                newWin.focus();
                newWin.print();
                newWin.close();
            },
            error: function (){ alert('An error occured'); }
    });
}

task_state(task_id);

As for the urls.py:

url.py

url(r'^ajax/task_state/$', task_state, name='validate_task_state'), # for ajax

And from the view:

admin_scripts.py

def task_state(request):
    print ("You reached the task_state function")
    data = 'Fail' 
    task_id = request.GET.get('task_id') 
    
    try:
        async_result = AsyncResult(task_id)
    except KeyError:
        ret = {'error':'No optimisation (or you may have disabled cookies).'}
        return HttpResponse(json.dumps(ret))

    print ("request.is_ajax(): {0}".format(request.is_ajax()))
    if request.is_ajax():
        if 'task_id' in request.POST.keys() and request.POST['task_id']:
            task_id = request.POST['task_id']
            async_result.get() 
            data = {
            'state': async_result.state,
            'result': async_result.result,
            }
        else:
            data = 'No task_id in the request'
    else:
        raise SuspiciousOperation("This is not an ajax request.")

    json_data = json.dumps(data)
    return HttpResponse(json_data, content_type='application/json')

Despite grappling with unresolved issues within the task_state, I am determined to navigate through this using trial and error. Currently, I'm experiencing difficulties in executing the task_state. The root cause seems to be linked to the AJAX call ('url'), but the exact problem remains elusive. Can someone help identify my mistake?

Update: Upon selecting the "JS Test Stuff" checkbox, the success.html page renders without errors. Both JavaScript files, including update-hello-user.js, are successfully called from success.html. Although the window generated by task_output_retrieval.js pops up, the view isn't triggered:

    $.ajax({
                url: query_url,
)

This specific section doesn't get rendered. In the console output, the following messages are logged:

[17/Aug/2018 04:59:12] INFO [django.server:124] "GET /MyApp/opt/ HTTP/1.1" 200 6631
async_result f2224e67-3e47-4980-9dc8-58622928e090
TASK_ID f2224e67-3e47-4980-9dc8-58622928e090
[17/Aug/2018 04:59:14] INFO [django.server:124] "POST /MyApp/opt/ HTTP/1.1" 200 6412
[17/Aug/2018 04:59:14] INFO [django.server:124] "GET /MyAppsite-static/MyApp/bootstrap/js/update-hello-user.js HTTP/1.1" 200 52
[17/Aug/2018 04:59:14] INFO [django.server:124] "GET /MyAppsite-static/MyApp/bootstrap/js/task_output_retrieval.js HTTP/1.1" 200 640

Answer №1

Upon reviewing your code, an issue that stands out to me is the placement of {% url validate_task_state %} within a JavaScript file. Typically, when setting up Django to serve static content using the recommended method, JavaScript files are not processed by the template engine, resulting in the template tag remaining unprocessed. Additionally, it necessitates quotes around its argument like so: {% 'url validate_task_state' %}

To resolve this, you should adjust your success.html template to pass the necessary URL to your task_state function as follows:

<script src="{% static 'MyAPP/bootstrap/js/task_output_retrieval.js' %}"></script>
<script type='text/javascript'> task_state("{% url 'validate_task_state' %}", "{{ task_id }}"); </script>

Furthermore, update your function to accept the new argument:

function task_state (query_url, task_id) {
    var taskID = task_id; 
    var newWin = window.open('', 'new window', 'width=200, height=100');

    $.ajax({
            url: query_url, 
            data: {'taskID':taskID},
            method: 'POST',
            dataType : "json",
            success: function(data){
                $(newWin.document.body).html(data);
                newWin.document.write(data);
                newWin.document.close();
                newWin.focus();
                newWin.print();
                newWin.close();
            },
            error: function (){ alert('An error occured'); }
    });
}

You mentioned that Django is unable to detect the request. One common reason for this is CSRF protection: when making a custom POST request, the CSRF token must be included, or else the request will be rejected. To address this, you can try the following approach:

// Obtain the CSRF token from the cookie.
var csrftoken = $.cookie('csrftoken');
$.ajax({
  type: "POST",
  url: "... my url ...",
  headers: {
    // Include the token in the request.
    'X-CSRFToken': csrftoken
  },
  // other ajax options...
});

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

When refreshed using AJAX, all dataTable pages merge into a single unified page

I followed the instructions on this page: How to update an HTML table content without refreshing the page? After implementing it, I encountered an issue where the Client-Side dataTable gets destroyed upon refreshing. When I say destroyed, all the data ...

Creating a looping animation on multiple elements using jQuery that makes them fade in and out at different intervals

I am currently working on creating a fade in and out animation for multiple elements using jquery. It's a bit complex to explain, so I will start by sharing the relevant code. $(document).ready(function() { $("#1").delay(0).animate({ ...

It appears that when importing from a shared package in lerna, the name must include "src" at the end for Typescript or Javascript files

I am currently working on a straightforward lerna project structure as shown below: Project | +-- packages | | | +-- shared | | | | | +-- src | | | | | +-- index.ts | | +-- someDir | | | +-- usesShared | ...

Troubleshooting CSS Carousel Navigation Problems

{% extends 'shop/basic.html' %} {% load static %} {% block css %} .col-md-3 { display: inline-block; margin-left:-4px; } .carousel-indicators .active { background-color: blue; } .col-md-3 img{ width: 227px; ...

Remove the class upon clicking

I recently created a toggle-menu for my website that includes some cool effects on the hamburger menu icon. The issue I am facing is that I added a JavaScript function to add a "close" class when clicking on the menu icon, transforming it into an "X". Whil ...

Ensuring promise resolutions in a chain using Angular JavaScript before delivering a final result

I have a scenario in Angular where I am using a chain of promises and I want to ensure that a value is returned at the end of the chain: this.calculateeventsattended = function(username) { var Attendees = Parse.Object.extend("Attendees"); var User = ...

Retrieve distinct values for the keys from an object array in JavaScript

Here is the structure of my array: const arr1 = [ { "Param1": "20", "Param2": ""8", "Param3": "11", "Param4": "4", "Param5": "18", ...

A correct JSON format for presenting information within an AngularJs framework

I am looking to integrate JSON data into my website using AngularJs. Here is the approach I have taken: First, I created a database in phpMyAdmin. Next, I set up a table with two columns - subject and body. Should an id column be included? After work ...

What methods can I use to conceal #! from showing on the browser's address bar?

Imagine you have the below link: www.someurl.com/#!?page=index How would you convert it into one of these options: www.someurl.com/#!/index (using mod_rewrite) www.someurl.com/ajax/index (also using mod_rewrite, but replacing #! with ajax) www.someurl. ...

Error: ChunkLoadError encountered when trying to load the "blogs-component" chunk in Laravel Vuejs

Despite smooth functioning on local development, my Laravel + Vuejs project is encountering ChunkLoadError on 2 pages. After consulting similar cases on SO and confirming the file's existence in the output path, the issue persists. The affected page ...

Navigating to a URL in the active tab using the Firefox WebExtension API

Embarking on the journey of creating a Firefox web extension/add-on has been an exciting experience for me. However, I am facing some challenges when it comes to navigating to a URL in the active tab. I have tried using document.open('https://www.gith ...

Exploring the distinctions between Django template variables and JavaScript variables

I am currently trying to populate a table in a Django template. The challenge I am facing is comparing cell values between a JavaScript variable and a Django template variable within the same context. Is there a way to perform this comparison without conve ...

Combining TypeScript and JavaScript for efficient mixins

I came across an article on MDN discussing the usage and creation of mix-ins (link). Intrigued, I decided to try implementing it in TypeScript: type Constructor = new (...args: any) => any; function nameMixin(Base: Constructor) { return class extends ...

Troubleshooting OpenCart Error Redirects with UserFrosting

Hi there! I've been working on a project where I'm integrating OpenCart into UserFrosting. Specifically, I'm loading all the admin dashboard pages within the UserFrosting dashboard using jQuery's .load function to inject them into a div ...

Incorporate validation features within a jQuery method

I am struggling with some HTML and jQuery code that generates links based on user input. HTML <input type="text" id="text" placeholder="Enter text" autofocus /> <a id="link1" class="btn btn-info" href="#" target="_blank"> Search 1 </a> ...

Is there a way to trigger the animation of this text effect only when the mouse is scrolled to that specific section?

Here is a cool typing text effect created using HTML, CSS, and JavaScript. Check out the code below: (function($) { var s, spanizeLetters = { settings: { letters: $('.js-spanize'), }, init: function() { ...

Having difficulty accessing information on utilizing .htaccess

Below is the .htaccess code I am currently using: RewriteEngine On RewriteRule ^([a-zA-Z0-9-_]+)$ topics.php?cat=$1 RewriteRule ^([a-zA-Z0-9-_]+)/$ topics.php?cat=$1 RewriteRule ^([^/]*)/([^/]*)$ /topics.php?cat=$1&bsid=$2 RewriteRule ^([^/]*)/([^/ ...

Organize table information using rowspan functionality

View of Current Table I am looking to implement a side column in my table using rowspan to group dates within each pay period. The goal is for a supervisor to be able to create a new pay period, which will assign a unique integer in the database and then ...

Webpack 5 is unable to load animated gif files

Hello, I am currently diving into webpack and following the official documentation at https://webpack.js.org/guides/asset-management/#setup. My goal is to incorporate an animated gif using webpack 5. Although the placeholder for the gif is loading, I enco ...

Exporting data acquired from a MongoDB query using Node.js

I am currently working on exporting the contents of a MongoDB collection by using exports.getAllQuestions = async function (){ MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("Time4Trivia"); ...