skip to Main Content

I want to submit a form using AJAX and without using jquery.. my form action is “/generate/transaction” and method=”POST”. When I submit the form, the url changes to ‘localhost/generate/transaction’ which I don’t want. I think on submit the event is not triggering, why so?

EDIT:
I am getting TypeError: tranForm is null error on the console.
Flask codeenter code here

from flask import Flask, render_template, jsonify, request
from collections import OrderedDict

class Transaction:
    def __init__(self, sender_public_key, sender_private_key,
                 recipient_public_key, value):
        self.recipient_public_key = recipient_public_key
        self.sender_public_key = sender_public_key
        self.sender_private_key = sender_private_key
        self.value = value

    def to_dict(self):
        return OrderedDict({
            'sender_public_key': self.sender_public_key,
            'sender_private_key': self.sender_private_key,
            'recipient_public_key': self.recipient_public_key,
            'amount': self.value,
        })
@app.route('/make/transaction')
def make_transation():
    return render_template('./make_transaction.html')


@app.route('/generate/transaction', methods=["POST"])
def generate_transation():
    sender_public_key = request.form["pub-key-f-tra"]
    sender_private_key = request.form["pri-key-f-tra"]
    recipient_public_key = request.form["rcvr-pub-key-f-trac"]
    amount = request.form["amt-f-trac"]

    # instantialing Transaction
    transaction = Transaction(sender_public_key, sender_private_key,
                              recipient_public_key, amount)

    response = {
        'transaction': transaction.to_dict(),
        'signature': 'random-sign-needstobe-updated'
    }
    return jsonify(response), 200
const tranForm = document.querySelector("#tran-form");
const senderPubKey = document.querySelector(".pub-key-f-tra");
const senderPriKey = document.querySelector(".pri-key-f-tra");
const rcvrPubKey = document.querySelector(".rcvr-pub-key-f-trac");
const amtToSend = document.querySelector(".amt-f-trac");
const tranBtn = document.querySelector("tran-form-btn");

// event listener
tranForm.addEventListener('submit', tranAjax);


function tranAjax(e) {
    e.preventDefault();

    const xrh = new XMLHttpRequest();

    xrh.onload = function () {
        if (this.status === 200) {
            console.log('form has been submitted!')

        } else {
            console.error();
            alert("An error occured");
        }
    }

    xrh.open("POST", "/generate/transaction", true);
    // to send POST request
    xrh.setRequestHeader("Content-type", "application/json");

    var data = JSON.stringify({
        'sender_public_key': senderPubKey.value,
        'sender_private_key': senderPriKey.value,
        'recipient_public_key': rcvrPubKey.value,
        'amount': amtToSend.value
    });
    xrh.send(data);
}
<html>
<head></head>
<body>
<form id="tran-form"  action="/generate/transaction" method="POST">
                <label for="sndr-pub-key" class="block float-left">Your Public Key: </label> 
                <input type="text" name="pub-key-f-tra" required class="pub-key-f-tra block border w-full p-2 hover:border-blue-500"></input>
                
                <label for="sndr-pri-key" class="block float-left">Your Private Key: </label> 
                <input type="text" name="pri-key-f-tra" rows="2" required class="pri-key-f-tra block border w-full p-2 hover:border-blue-500"></input>
                
                <label for="rcvr-pub-key" class="block float-left">Receipent Public Key: </label> 
                <input type="text" name="rcvr-pub-key-f-trac" rows="2" required class="rcvr-pub-key-f-trac block border w-full p-2 hover:border-blue-500"></input>
                
                <label for="tran-amt" class="block float-left">Amount: </label> 
                <input type="text" name="amt-f-trac" rows="1" required class="amt-f-trac block border w-full p-2 hover:border-blue-500"></input>
                
                <button type="submit" id="tran-form-btn" class="transaction-btn bg-blue-700 my-2 py-2 px-3 text-white hover:bg-gray-800 hover:rounded">
                    Generate Transaction
                </button>
</form>
</body>
</html>

2

Answers


  1. Why you don’t simple use onsubmit

        <form onsubmit="myFunction()" method="POST">
            Enter name: <input type="text">
            <input type="submit">
        </form>
    
    Login or Signup to reply.
  2. Try to wrap your code inside window.onload. Events won’t work unless your document loads completely.

    window.onload = function () {
                const tranForm = document.querySelector("#tran-form");
                const senderPubKey = document.querySelector(".pub-key-f-tra");
                const senderPriKey = document.querySelector(".pri-key-f-tra");
                const rcvrPubKey = document.querySelector(".rcvr-pub-key-f-trac");
                const amtToSend = document.querySelector(".amt-f-trac");
                const tranBtn = document.querySelector("tran-form-btn");
    
                // event listener
                tranForm.addEventListener('submit', tranAjax);
    
    
                function tranAjax(e) {
                    e.preventDefault();
    
                    const xrh = new XMLHttpRequest();
    
                    xrh.onload = function () {
                        if (this.status === 200) {
                            console.log('form has been submitted!')
    
                        } else {
                            console.error();
                            alert("An error occured");
                        }
                    }
    
                    xrh.open("POST", "/generate/transaction", true);
                    // to send POST request
                    xrh.setRequestHeader("Content-type", "application/json");
    
                    var data = JSON.stringify({
                        'sender_public_key': senderPubKey.value,
                        'sender_private_key': senderPriKey.value,
                        'recipient_public_key': rcvrPubKey.value,
                        'amount': amtToSend.value
                    });
                    xrh.send(data);
                }
            }
    <form id="tran-form" action="/generate/transaction" method="POST">
            <label for="sndr-pub-key" class="block float-left">Your Public Key: </label>
            <input type="text" name="pub-key-f-tra" required
                class="pub-key-f-tra block border w-full p-2 hover:border-blue-500"></input>
    
            <label for="sndr-pri-key" class="block float-left">Your Private Key: </label>
            <input type="text" name="pri-key-f-tra" rows="2" required
                class="pri-key-f-tra block border w-full p-2 hover:border-blue-500"></input>
    
            <label for="rcvr-pub-key" class="block float-left">Receipent Public Key: </label>
            <input type="text" name="rcvr-pub-key-f-trac" rows="2" required
                class="rcvr-pub-key-f-trac block border w-full p-2 hover:border-blue-500"></input>
    
            <label for="tran-amt" class="block float-left">Amount: </label>
            <input type="text" name="amt-f-trac" rows="1" required
                class="amt-f-trac block border w-full p-2 hover:border-blue-500"></input>
    
            <button type="submit" id="tran-form-btn"
                class="transaction-btn bg-blue-700 my-2 py-2 px-3 text-white hover:bg-gray-800 hover:rounded">
                Generate Transaction
            </button>
        </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search