Utilizing AJAX to send RSS feeds to a Django view

I'm fairly new to using ajax. Here's the scenario I'm dealing with: I'm working on a side project that involves displaying news and scores for various sports. To achieve this, I'm utilizing rss feeds from different sources. In my Django views, I can fetch and parse the rss feeds using the 'feedparser' plugin, then pass them as context to the corresponding template. Below is my view function and template (for cricket).

def cricket(request):
    feeds_cric = feedparser.parse('http://www.espncricinfo.com/rss/content/story/feeds/0.xml') #espncricinfo feed.
    feeds_cric_scores = feedparser.parse('http://static.cricinfo.com/rss/livescores.xml') #espncricinfo feed.
    context = {'feeds_cric': feeds_cric,'feeds_cric_scores' : feeds_cric_scores}
    return render(request,'scorecenter/cricket.html', context)

Below is the corresponding template.

{% extends "scorecenter/index.html" %}
{% block content %}
    <ul>
        {% for entry in feeds_cric.entries %}
        <li><a href="{{ entry.link }}">{{ entry.title }}</a></li>
        <p>{{ entry.description }}</p>
        {% endfor %}
    </ul>

{% endblock content %}

{% block score %}
    <ul>
        {% for entry in feeds_cric_scores.entries %}
        <li><a href="{{ entry.link }}">{{ entry.title }}</a></li>
        <!-- <p>{{ entry.description }}</p> -->
        {% endfor %}
    </ul>
{% endblock score %}    

This is the index.html file.

Now, I want to implement AJAX to refresh only specific sections of my page without reloading or redirecting the whole page. I have written a script to check the

<body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" href="#">Allscores</a>
            </div>
            <div>
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#" onclick="urlChecker('cricket')">Cricket</a></li>
                    <li><a href="#" onclick="urlChecker('football')">Football</a></li>
                    <li><a href="#" onclick="urlChecker('basketball')">Basketball</a></li>
                    <li><a href="#" onclick="urlChecker('tennis')">Tennis</a></li>
                </ul>
            </div>
        </div>
    </nav>
    <div class="navbar navbar-default" id="empty_nav"></div>

    <div class="testingData" gt;This should be updated</div>

    <div class="row">
        <div class="col-sm-8" id="news">

            <h3>Latest News</h3>
            {% block content %}
            {% endblock content %}

        </div>
        <div class="col-sm-4" id="scores">

            <h3>Latest scores</h3>
            {% block score %}
            {% endblock score %}

        </div>
    </div>

    <div id="footer">
        Copyright © acllscores.com
    </div>
</body>

In my urlChecker() script, it evaluates which anchor tag was clicked and assigns the corresponding url. Here is the script:

function urlChecker(route) {
    switch(route) {
        case 'cricket':
            $.post( "/scorecenter/cricket/", function( data ) {
                $( ".result" ).html( data );
            });
            break;
        case 'football':
            $.post( "/scorecenter/football/", function( data ) {
                $( ".testingData" ).html( data );
            });
            break;
        case 'tennis':
            $.post( "/scorecenter/tennis/", function( data ) {
                $( ".testingData" ).html( data );
            });
            break;
        case 'basketball':
            $.post( "/scorecenter/basketball/", function( data ) {
                $( ".testingData" ).html( data );
            });
            break;

    }
}

Update: Addition of urls file:

urlpatterns = patterns('',
    url(r'^$', views.index,name='index'),
    url(r'^test/$', views.test,name='test'),

    url(r'^cricket/$', views.cricket,name='cricket'),
    url(r'^basketball/$', views.basketball,name='basketball'),
    url(r'^football/$', views.football,name='football'),
    url(r'^tennis/$', views.tennis,name='tennis'),

)

I am unsure how to use AJAX to post the feed data to my templates. Any assistance would be appreciated.

Answer №1

Looking at Ajax Differently

The question suggests that a GET request would be more suitable than a POST request from the Ajax perspective. In this scenario, you are simply retrieving updates from endpoints rather than sending any data to be stored. Transitioning from $.post() to $.get() should seamlessly integrate into your existing code.


Considering Django's Viewpoint

Opting for a GET request is straightforward as it eliminates the need to handle ☞ Django's CSRF protection. While working with other ajax requests like POST, DELETE, etc., you will have to include an additional step of sending the CSRF token with each request, as explained thoroughly in the provided documentation.


Rendering Results from Ajax Requests

There might be a potential issue with how the template, such as scorecenter/cricket.html, renders the Ajax results. By extending from index.html, every request returns not only the desired html block but also content from index.html. When inserting results using Javascript, templates should focus solely on rendering the specific html to be inserted into the DOM using $('.testingData').html(data).


Troubleshooting Ajax Request Challenges

During site development, utilize the developer tools and console in browsers like Firefox or Chrome to examine any errors resulting from failed Ajax-requests. Errors may manifest as 404 (endpoint not found), 400 or

403</code (authorization issues), or <code>500
(server error). Refer to ☞ More comprehensive list of status codes for further insights.

Enhance your question with additional specifics if needed. Given the breadth of this topic, acknowledge that it could potentially lead to closure by the community. Should this occur, seek out more targeted inquiries or create new questions if warranted.

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

What could be the reason my bootstrap cards are stacking vertically instead of being placed horizontally next to each other?

My Bootstrap cards are not aligning side by side and I'm having trouble locating the error in my code. I'm working with Django and HTML. {% extends 'base.html' %} <div> {% block content %} <h1>Team Members<h1& ...

JavaScript obtain scroll position of a child element

I have a setup that looks something like the following: <div> <div id="scrollID" style="height:100px;"> content here </div> </div> <script> document.getElementById("myDIV").addEventListener("touchstart", m ...

"The Role of Browser Helper Objects in Enhancing AJAX Functionality

I was questioning whether or not the BeforeNavigate2 or DocumentComplete events should trigger on pages utilizing AJAX, such as Google Maps. When I input something into the address bar, everything works fine. However, when I move and resize the map, no e ...

What is the process by which browsers manage AJAX requests when they are made across

I have encountered an issue that is puzzling to me, and I suspect it might be due to my misunderstanding of how the browser handles AJAX requests. Just for context, I am using Codeigniter on an Apache server and triggering AJAX requests with jQuery. The b ...

New elements can be inserted at the rear of the queue while older elements are removed from the front of the queue

I'm new to JavaScript and currently working on a task involving queues. Here is the task description: Create a function called nextInLine that takes an array (arr) and a number (item) as parameters. The function should add the number to the end of ...

When setValue is called on VCheckbox in Vuetify, it emits an event called "update:modelValue"

After setting a value for the checkbox, I encountered a warning message: [Vue warn]: Component emitted event "update:modelValue" but it is neither declared in the emits option nor as an "onUpdate:modelValue" prop. Example.vue <script setup lang="t ...

The process of extracting values from an HTML tag using Angular interpolation

I am working on an Angular application that has the following code structure: <p>{{item.content}}</p> The content displayed includes text mixed with an <a> tag containing various attributes like this: <p>You can find the content ...

Executing a service prior to the loading of Angular 7 applications or components

Currently, I am in the process of developing an application using Angular 7. So far, everything is running smoothly as I have successfully managed API calls, JWT Token authentication with C#, and updating LocalStorage when needed during user login and logo ...

What is the most effective method to include JSON data containing various IDs at the end within an $http.get() request in AngularJS?

I'm facing a challenge with displaying JSON items that have an array of different ids at the end of the URL (/api/messages/:messageId). For instance, accessing /api/messages/12345 would return {"subject":"subject12345","body":"body12345","id":"12345"} ...

Possible solutions for AngularJS using ng- tags

I absolutely love incorporating AngularJs into my Multiple Pages Laravel Application. However, using the Laravel Blade Template Engine has made me reconsider adding Angular Tags to clutter my blade templates. For instance <div ng-controller="TodoCont ...

Changing the text during a reset process

I've been grappling with this issue, but it seems to slip through my fingers every time. I can't quite put my finger on what's missing. My project involves clicking an image to trigger a translate effect and display a text description. The ...

Using jQuery to pass dynamic values to a plugin function

I'm currently utilizing the JSONTable plugin and attempting to dynamically pass values to the 'head' and 'json' parameters by extracting them from an array object. For instance, I aim to load a new json file, convert it to a JavaSc ...

Submitting the form without utilizing Ajax, but instead sending data directly to a PHP script

I've encountered an issue while posting a form to a PHP file using AJAX. Despite my efforts, the form is bypassing AJAX and posting directly to the PHP file. Here is my form: <form id="editform" name="editform" action="ajaxeditform.php" method= ...

sending a variable from routes.js to my .ejs template

I need help figuring out how to display user information from my database in a template. var aboutUser = connection.query("SELECT about FROM users WHERE username = ?", req.user, function(err, rows) {});` I want to pass this data to the template like so: ...

The issue of actions failing to flow from sagas to reducers in React.js

Upon user login, the success response is received but the action is not passed to the reducer. Strangely, during user registration, everything works smoothly. //saga.js import { put, takeEvery, all, call } from 'redux-saga/effects'; import {getRe ...

halt execution of npm test and erase any printed content

When I run npm test on my React project, it runs unit tests using jest and react testing library. The test logs (including console log lines added for debugging) are printed to the screen but get deleted after running the tests. It seems like the logs are ...

Receive the Navigating event upon a new browser window opening with the help of the WebBrowser control in JavaScript

In my C# / .NET 4 project, I have a form containing a WebBrowser component that loads an external web page. An event handler is connected to the Navigating event which usually works well. However, there is an issue when a specific part of the loaded websi ...

Change from one value to another using a decaying sinusoidal wave

Can someone help me come up with a formula that will smoothly transition from a starting value to an end value over a specified time using a Sin or Cos wave? I'm attempting to replicate a bouncing effect like the one shown in my sample using CSS and ...

What is the best way to incorporate a custom event listener into my React Native component?

Hello everyone, I am currently working with React Native+Expo and have created a custom component called a stepper. Here's how it looks: Below is the code for this custom stepper: import React, { useState } from 'react'; import { View, Text ...

Getting the http response content of a Slim PHP API with Angular JS: A step-by-step guide

My Slim PHP programmed API sends JSON responses in the following format: $response['some-text'] = 'blabla'; $app->response->setStatus(200); $app->response()->headers->set('Content-Type', 'application/json& ...