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

1👍

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
    }
👤Arthur

Leave a comment