PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 27, 2022

[FIXED] How to send data from the front-end to the back-end using ajax and Dango?

 October 27, 2022     ajax, django, javascript, jquery, python     No comments   

Issue

INTRO: I am writing a Django application which needs to send some data from the front-end to a views.py file in the back-end. To do so, I have a button which performs a transaction when clicked. This is what it looks like:

<button id="submit_transaction" type="button" class="btn btn-outline-info" onclick="transaction()">Transaction</button>

PROBLEM: When clicked, the button triggers a function called transaction() which performs an asynchronous operations, like so:

<script>
    async function transaction(){
    // Perform some task

    // Submit transaction
    $.ajax({
          type: 'POST',
          data : {
              'public_key': public_key,
          },
          success: function(res){
            console.log(res);
          }
        });
    }
</script>

Inside of this asynchronous function there is an ajax call which collects some data into a variable and then sends it to the back-end via a post request (as suggested here link).

However when I click the button the following error pops up:

Uncaught (in promise) TypeError: Illegal invocation

QUESTION: Do you have any idea of what I am doing wrong? or are you able to suggest a smart and elegant solution to send some data from the front end to the back-end?


Solution

You need to provide an url

<script>
    
    body = {
        'csrfmiddlewaretoken': crsfToken,
        'public_key': ...
    }

    async function transaction(){
    // Perform some task

    // Submit transaction
    $.ajax({
          url: 'https://mysite',
          type: 'POST',
          data : body,
          success: function(res){
            console.log(res);
          }
        });
    }
</script>

You also have to provide the csrf_token if you want your django view to accept the request (or use csrf_exempt which is less secure)

I do recommend using the Request standard JS library over Ajax because Request is native. You can find more documentation here : https://developer.mozilla.org/en-US/docs/Web/API/Request/Request

Here's an example of how I use Request :

/**
     * Send some data to create an object in my db.
     * @param data what's created.
     * @returns {*} what was created server-side.
     */
    async create(data) {
        let res = await fetch(new Request('https://my.create.url', {
            method: 'POST',
            body: data,
            headers: {
                'X-CSRFToken': this.csrfToken,
                'Content-Type': "application/x-www-form-urlencoded" // required if you want to use request.POST in django
            }
        }));
        if (res.status === 201) {
            return res.text(); // Status (because I return HttpResponse(status=201) )
        }
        if (res.status === 400) {
            throw new InvalidFormError("form invalid", await res.text());
        }
        throw new Error(await res.text()); // You have to handle it afterward
    }



Answered By - Arthur
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing