Using Django with Ajax without the need for the JQuery library

Exploring the world of Ajax without jQuery Library has been quite a journey. I recently created a basic view that displays a random number on the screen. After adding a button and invoking the ajax function, I encountered an issue where clicking the button did not update the displayed value. Upon inspecting the DOM (using firebug), I discovered that the someText.responseText was returning the entire HTML instead of just the new value. Despite my efforts, like checking "request.is_ajax()" and examining the request for any signs of ajax, I couldn't seem to make it work as expected. This experience has brought me face to face with the complexities of Django and how to handle them effectively.

I have shared snippets of my code below:

def home(request):
    rand_num = random.randint(1, 100)
    return render(request, 'home.html', {'rand_num': rand_num})

And here is the corresponding HTML and script:

<html>
<head>
<script type='text/javascript'>
    var someText;
    function helloWorld(){
        someText = new XMLHttpRequest();
        someText.onreadystatechange = callBack;

        someText.open("GET", "{% url 'home' %}", true);
        someText.send();
    };

    // Handling server response
    function callBack(){
        if(someText.readyState==4 && someText.status==200){
            document.getElementById('result').innerHtml = someText.responseText;
        }
    };
</script>

</head>
<body>
<div id="result">{{ rand_num }}</div>
<input type='button' value='Abraca dabra!' onclick="helloWorld()"/>

</body>
</html>

Lastly, here is the URL mapping for the view in question:

url(r'^$', 'socialauth.views.home', name='home'), 

As I continue learning through online tutorials, your guidance and support are highly appreciated.

Answer №1

Instead of requesting the whole rendered template in your AJAX call, create a new view and URL to return only the number you need.

AJAX is simply a method for making asynchronous requests to URLs and retrieving the response content. To achieve this, consider creating a view using JSONResponse:

from django.http import JsonResponse

def get_random_number_json(request):
    random_no = random.randint(1,100)
    return JsonResponse({'random_no': random_no})

In your frontend Javascript, fetch the URL for this specific view to receive just the JSON data you require. This simplifies your code by allowing you to directly access the variable from the JSON object instead of processing the entire document.getElementById('result').

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

Guide on incorporating a refresh button to automatically update information from a database in MaterialUI's Datagrid

Recently diving into JavaScript, I encountered a common issue: The data for my table is sourced from a MySQL database through Axios Whenever CRUD operations are performed in the web app, the database is updated accordingly Although backend changes ...

Taking steps when a number is enclosed within a span

Testing a simple code with similar action to what I want. Apologies for any language errors, hoping to be understood :-) The HTML code snippet: <div class="pagination"> <a href="#" class=""><span>1</span></a> <a href=" ...

Tips for utilizing AJAX to send data from a specific row

<table> <tr data-id="1"> <input type="text" name="name_1" value="abc"> <input type="text" name="value_1" value="1"> <a href="load_edit_row(this)">Edit</a> </tr> <tr data-id="2"> <input t ...

Difficulty with obtaining .responsetext in AJAX and PHP

On my real estate website, I have a form for users to 'Add a Property'. Although I will implement form validation later on, here is the current html/js code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR ...

Incorrect data retrieval from JSON object with JQUERY

I am working on a function that extracts data from a database on the server-side and assigns it as the value of a textbox on the client-side. The function is functioning correctly on the server-side, but on the client-side, when I use console.log to view t ...

Tips for integrating Twitter sharing functionality in React JS

I am looking for a way to enable users to easily share images from my website on Twitter. Although I tried using the react-share module, it does not provide an option to directly share images. This is the snippet of code I currently have: import { Sh ...

Exploring the functionality of the instanceof operator in Javascript

I'm currently developing a Node.js application and the project structure is as follows: [Project Folder] | |---[plc] | |--- plc.js | |--- scheduler.js | |---[source] | |--- source.js | |---[test] |--- test.js Th ...

Dynamic Select Box with Display of 2 Buttons

Looking to create an Ajax combo box with options for Female and Male. I would like to display a button for Female and a button for Male. Here is the code that I have: <!DOCTYPE html> <html> <head> <style> #for-male, #for-female{ ...

Having trouble accessing the downloaded file from S3 using Angular and NodeJS

Currently, I am facing an issue while attempting to download a jpg image from amazon S3 using the NodeJs SDK. Although I can successfully retrieve the file object on the backend, encountering difficulties arises when trying to create a blob object and down ...

What is the best way to reduce the size of a Base64/Binary image in Angular6

I utilized the Ngx-Webcam tool to capture images from my camera. My goal is to obtain both high quality and low quality images from the camera. Although this library provides me with Base64 images, it offers an option to reduce the size using imageQuality ...

Ways to require semicolons in a Typescript interface

When declaring a TypeScript interface, both , (comma) and ; (semicolon) are considered valid syntax. For example, the following declarations are all valid: export interface IUser { name: string; email: string; id: number; } export interface IUser { ...

Is there a feature in VS Code that can automatically update import paths for JavaScript and TypeScript files when they are renamed or

Are there any extensions available for vscode that can automatically update file paths? For example, if I have the following import statement: import './someDir/somelib' and I rename or move the file somelib, will it update the file path in all ...

Why is my Angular form submitting twice?

Currently, I am working on a user registration form using AngularJS with ng-submit and ng-model. However, I am facing an issue where the form triggers submission twice when the user submits it. I have checked for common causes such as declaring the contro ...

Decoding various JSON arrays received through AJAX requests

After returning two objects as JSON through AJAX, I am facing an issue with accessing the values in these two lists. Previously, when I had only one list, I could parse it easily. data = serialize("json", vm_obj) data2 = serialize("json", user_networks_li ...

Utilize Lodash to iterate through functions in a loop and retrieve the first matching result

I am looking to iterate through an array of objects and call a method on them. If the result of that method meets certain conditions, I want to immediately return that result. The current implementation is as follows: public getFirstMatch(value: string, a ...

Using jQuery's slideToggle feature to hide content when clicked again or when a different button is

I have a challenge with creating toggle buttons that require specific functions: 1) Display content on the first click (this is working) 2) Conceal content when another button is clicked (this is also working) 3) Hide content on the second click (this i ...

Exploring the world of Node.js, JSON, SQL, and database tables

Hello everyone, I have been working on a project using Node.js and Express framework. My current goal is to create a client-side page that allows users to input form data into a MySQL database. I have managed to successfully insert and retrieve data from ...

Is it possible to update the variable value in one controller from another controller after an http.get request has been made

I have encountered an issue with updating a variable from one controller to another using a service. Despite my efforts, the variable is not being updated. The goal is to have the variable $scope.names in controller 'select' update in controller ...

Changing the border of an iframe element using jQuery or Javascript from within the iframe itself

Is it possible to set the border of an iframe to zero from within the iframe itself using JavaScript or jQuery? Any guidance on how this can be achieved would be greatly appreciated. Thank you! ...

Uncertain about the process of accessing req.body data

I'm having trouble retrieving the body data on my server, even with simple .get requests. Despite simplifying it to just a basic call, I still can't seem to access the body data. This issue is hindering more complex calls that require accessing t ...