Sending a JavaScript object for processing on a Django backend: Step-by-step guide

I posted a question earlier, but it turned out to be more complex than I anticipated. In order to simplify things, here's the revised version of my question. I am currently working on payment processing using a JavaScript API and receiving the results successfully. However, I need to send these results to a Django backend for further processing. Due to my limited knowledge of JavaScript/Django interaction, I'm encountering some difficulties. Below are the relevant files:

Subscription.py This is a straightforward page that allows users to select their subscription.

@csrf_exempt
@login_required(login_url='login')
def subscription(request):
    user = request.user
    user_organization = OrganizationUser.objects.get(user=user)
    company = Company.objects.filter(name = user_organization.organization.name).first()
    today = datetime.date.today()
    form = CompanyForm(request.POST)
    subscription = Subscription.objects.all()

    if user_organization.is_admin == True:

        context = {'user_organization': user_organization, 'form': form, 
                'subscription': subscription, 'company': company, 'today': today,}
        return render(request, 'registration/subscription.html', context)
    else:
        return HttpResponse('You are not authorised to view this page')

And here is the corresponding Subscription.html file:

{% block content %} 

<div class="columns is-centered">

   <div class="column is-5 box">
  
    {% if company.paid_till < today %}
    <form action="" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <div class="content">
      
      <h1 class="title is-4">
          <i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
          Account is not active
      </h1>
      Your company <strong>{{user_organization.organization}}</strong> is not active. Please renew the subscription.<br>
    </div>
    {% else %}
    
    <p class="label">We have great subcription options for you. Choose from our list either for monthly or annual plans</p><br>

    {% endif %}
    <h2>Subscription Packages</h2><br>
    <div class="select"> 
      <select
        name="search"
        hx-get="{% url 'searched-subs' %}"
        hx-target="#searched-subs"
        hx-trigger="change"
        hx-swap="innerHTML"
        onchange="updateButtonDataAmount(event)"
      >
      <option value="select-a-plan">Select A Plan</option>
      <option value="7.99">Starter - Monthly ($7.99/Month)</option>
      <option value="79.00">Starter - Annually ($79.00/Year)</option>
      <option value="49.90">Business - Monthly ($49.90/Month)</option>
      <option value="499.00">Business - Annually ($499.00/Year)</option>
      </select>
    </form>
    </div><br><br>

    <div id="searched-subs"></div><br><be>
    
    <button class="intaSendPayButton button is-btn-mycolor is-fullwidth" 
    data-amount="10" 
    data-currency="KES" 
    data-email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ae0e5efcaeee5efa4e9e5e7">[email protected]</a>" 
    data-first_name="JOE" 
    data-last_name="DOE" 
    data-country="KE">
    Pay Now
    </button><br>
  
    </div>
    </div>

<script>


  new window.IntaSend({
    publicAPIKey: "publishing-key",
    live: false //set to true when going live
  })
  .on("COMPLETE", (results) => console.log("Payment in COMPLETE status", results))
  .on("FAILED", (results) => console.log("Payment in FAILED status", results))
  .on("IN-PROGRESS", (results) => console.log("Payment in progress status", results))
  </script>
  {% endblock %}

The code functions properly and displays the results from the payment event in the console. My challenge lies in finding a way to interact with the "results" within the subscription view above in order to process the payment event effectively. I've attempted various methods, but there seems to be a crucial element I'm overlooking.

Answer №1

Typically, when you want to transfer data from the browser to a server, you would initiate an HTTP request. In Django, you would create a regular view (request handler) to receive the request, extract the data from it, and perform some action with it. On the Javascript side, you would write code to send the necessary data in the request. To get started, familiarize yourself with using XMLHTTPRequest or the more modern fetchAPI in the browser. You can find helpful resources for learning at MDN and w3schools:

https://www.w3schools.com/js/js_ajax_intro.asp

https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

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

React -- What is causing this line to append instead of add?

Instead of seeking a different solution to the problem, I am interested in understanding why defining an integer still causes it to concatenate with .map as if it were a string. The data retrieved from an API is quite basic: "data":["8" ...

Guide on dynamically updating a div in PHP with a mix of text output and images at regular intervals

My current project involves creating a browser-based card game primarily using PHP, with potentially incorporating other languages to help me enhance and test my PHP skills. However, I've encountered difficulties while attempting to implement various ...

What is the best way to execute a .js file with a Mocha suite repeatedly within a loop?

I have a collection of .js test files and I am looking for a way to execute the tests in each file multiple times. Ideally, I would like to run them 5 or 10 times consecutively. Even if it's just one file at a time, but running it multiple times. I a ...

Sorting arrays in ES5 with the sort() method

In my array, I have multiple objects with a 'time' property that stores date strings. elements = [ {time: "2013-03-01T10:46:11Z"}, {time: "2013-03-03T10:46:11Z"}, {time: "2013-03-02T10:46:11Z"} ] My goal is to ...

Socket IO functions exclusively in development mode

I have successfully implemented the messaging feature in my application and it works perfectly in development mode. However, when I deployed the code on Heroku to test it in production mode, the messaging component stopped functioning. Messages are only re ...

Display or conceal a div when hovering over dropdown menu choices

$('#dropdown-list').on('change',function(){ if( $(this).val()==="option 1" ){ $("#diva").hide() } else { $("#divb").show() } }); The code above is being used to hide or show a div based on a dropdown selection, which is f ...

React Hook for modifying a value within an array of objects in real-time

Is there a way to update the score of each player with a simple click? I have already implemented the initial code and all that's left is to define the function that will trigger the score update for each user. The increment value is +1. const [p ...

Tips for revealing the pin after entering it into the text box

Is there a way to display the address inputted into 4 textboxes (with pin changing after onchange) on a Google map embedded on my website? I want to have 4 separate input fields for zip code, city, street, and house number. If all four boxes are filled out ...

The menuToggle feature works flawlessly on desktops after integrating my AngularJS module, but unfortunately, it is not functioning

I have successfully integrated autosuggestion using AngularJS material library into my web application. Everything seems to be working fine except for one issue. When I include ng-App="MyApp2", the menuToggle button stops functioning only on mobile devices ...

Front end data logging with Django and phidgets - a winning combination

How can Django be effectively used to build an application similar to OpenNMS or other network management tools? The Django app will need to continuously poll one or more devices, each with multiple analog and digital inputs. Essentially, the challenge l ...

Insert two backslashes before a single backslash in PHP

I have been looking for a solution everywhere and have experimented with the JavaScript replace() function, str_replace, addslashes, and stripslashes, but I still can't seem to get the desired output. Here is what I am attempting: str_replace("&bsol ...

Update the contents of TubeBufferGeometry with a new TubeBufferGeometry directly, avoiding unnecessary memory allocation

I am working with a mesh that is based on a TubeBufferGeometry. In each animation cycle, the path of the TubeBufferGeometry needs to change based on values provided at runtime. To achieve this, I want to update the geometry with a new TubeBufferGeometry ev ...

Customize Django's inline formset textInput size attribute

Currently, my inline formset consists of only three fields: class Estimate_Product_Details(models.Model): proposalID = models.ForeignKey(Estimate_Construction, verbose_name='Proposal ID') CID = models.ForeignKey(Product, verbose_name = & ...

Error: Action Not Permitted - Django REST Framework

Encountering an issue during the update process. Data can be added successfully, but there is an error specifically with the UpdateAPIView. { "detail": "Method \"POST\" not allowed." } urls.py path('groups/update/<int:pk>', ...

Tips for updating the corresponding nav link in CSS when transitioning between pages

In order to highlight the current page in the navigation menu, one method is to use an active attribute on the nav-link of the respective page: <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link navLink ...

Avoiding the use of MEDIA_ROOT and MEDIA_URL for a particular scenario

I have a query regarding changing MEDIA_ROOT under certain circumstances. Specifically, I am dealing with importing XML files that are quite large, exceeding 100 MB in size. Additionally, I am utilizing AWS for storing my uploaded media files. Whenever I u ...

Tips for testing views in ember.js using unit tests

We are currently delving into the world of Ember.js. Our development process is completely test-driven, and we aim to apply the same methodology to Ember.js. Having prior experience in test-driven development with Backbone.js apps using Jasmine or Mocha/Ch ...

Angular2's change detection mechanism does not behave as anticipated after receiving a message from a Worker

Within my angular2 application, I encountered a rather intriguing scenario which I will simplify here. This is AppComponnet export class AppComponent { tabs: any = []; viewModes = [ { label: "List View"}, { label: "Tree View" }, ...

Delete all references to a model in Django RESTful

I am trying to use the API to delete all records of a model, but I am encountering an error. How can I successfully achieve this? View : @api_view(["DELETE"]) @csrf_exempt @permission_classes([IsAuthenticated]) def delete_site(request): try: S ...

Having trouble with installing a React app using npx create-react-app my-app?

description needed for image Having trouble creating a react application using npx create-react-app my-app... Encountering errors shown in the image. Attempted npm init but it was unsuccessful. Included node.js and vs code in the path. ...