Прослушиватель событий отправки не работает (vanilla javascript) - PullRequest
0 голосов
/ 25 мая 2020

Я хочу отправить форму с использованием AJAX и без использования jquery .. мое действие формы - «/ generate / transaction» и method = «POST». Когда я отправляю форму, URL-адрес меняется на localhost / generate / transaction, что мне не нужно. Я думаю, что при отправке событие не запускается, почему так?

EDIT: Я получаю сообщение об ошибке TypeError: tranForm is null на консоли. Flask код enter code here

from flask import Flask, render_template, jsonify, запрос из коллекции 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 ]

0 голосов
/ 25 мая 2020

Попробуйте обернуть свой код внутри window.onload . События не будут работать, пока ваш документ не загрузится полностью.

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>
0 голосов
/ 25 мая 2020

Почему вы просто не используете onsubmit

    <form onsubmit="myFunction()" method="POST">
        Enter name: <input type="text">
        <input type="submit">
    </form>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...