Home > other >  How to send data from the front-end to the back-end using ajax and Dango?
How to send data from the front-end to the back-end using ajax and Dango?

Time:10-25

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"  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?

CodePudding user response:

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
    }

  • Related