OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

I cant send data from form

  • Thread starter Thread starter Milan Vidanovic
  • Start date Start date
M

Milan Vidanovic

Guest
i have a problem with sending data to my mail from form.I have a 2 form in my code, one is for "fizickaLica" one is for "pravnaLica". Now i have js code which send data from first form to my mail, but when I want to send data from second form i got my alert that said: "Došlo je do greške prilikom slanja podataka. Molimo pokušajte ponovo."("An error occurred while sending data. Please try again.") What should i do? This is my form

Code:
<div id="fizickaLica" class="tab1 active">
    <form class="form" id="checkoutForm">
        <div class="group">
            <label for="name">Ime</label>
            <input type="text" name="name" id="name" required oninvalid="this.setCustomValidity('Unesite ime i prezime')" oninput="this.setCustomValidity('')">
        </div>

        <div class="group">
            <label for="phone">Telefon</label>
            <input type="text" name="phone" id="phone" required>
        </div>

        <div class="group">
            <label for="address">Adresa</label>
            <input type="text" name="address" id="address" required>
        </div>

        <div class="group">
            <label for="country">Zemlja</label>
            <input type="text" name="country" id="country" required>
        </div>

        <div class="group">
            <label for="city">Grad</label>
            <input type="text" name="city" id="city" required>
        </div>
        <div class="g-recaptcha" data-sitekey="6Ldkjf8pAAAAAJ77ZZn3qOnfd17dU0kjN0847L1m"></div>
        <button class="buttonCheckout submit" id="checkoutButton" type="submit" action="index.html">Poruči</button><br>
        <input type="hidden" name="list" id="list">
        <input type="hidden" name="totalPrice" id="totalPrice">
    </form>
</div>

<div id="pravnaLica" class="tab1">
    <form class="form" id="checkoutFormPravna">
        <div class="group">
            <label for="companyName">Naziv firme</label>
            <input type="text" name="companyName" id="companyName" required>
        </div>

        <div class="group">
            <label for="contactName">Kontakt osoba</label>
            <input type="text" name="contactName" id="contactName" required>
        </div>

        <div class="group">
            <label for="phone">Telefon</label>
            <input type="text" name="phone" id="phone1" required>
        </div>

        <div class="group">
            <label for="address">Adresa</label>
            <input type="text" name="address" id="address1" required>
        </div>

        <div class="group">
            <label for="country">Zemlja</label>
            <input type="text" name="country" id="country1" required>
        </div>

        <div class="group">
            <label for="city">Grad</label>
            <input type="text" name="city" id="city1" required>
        </div><br>
        <div class="group">
            <input type="checkbox" id="privacyCheck" required>
            <label for="privacyCheck">Slažem se sa <a href="pravila-privatnosti.html">pravilom privatnosti</a></label><br>
        </div>
        <div class="g-recaptcha" data-sitekey="6Ldkjf8pAAAAAJ77ZZn3qOnfd17dU0kjN0847L1m"></div>
        <button class="buttonCheckout submit" id="checkoutButton1" type="submit" action="index.html">Poruči</button><br>
        <input type="hidden" name="list" id="list1">
        <input type="hidden" name="totalPrice" id="totalPrice1">
    </form>
</div>

and I have cuple of js files but for this problem just 2 was importanr my server.js

Code:
const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const path = require('path');
require('dotenv').config(); // Učitaj .env datoteku

const app = express();
const port = 3000;

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Serve static files from the root directory
app.use(express.static(path.join(__dirname)));

// Serve the 'checkout.html' file as the default page
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'checkout.html'));
});

// Endpoint to handle form submission
app.post('/send-email', (req, res) => {
    const { name, phone, address, country, city, companyName, contactName, list, totalPrice } = req.body;

    const currentDateTime = new Date().toLocaleString();

    // Extract product names and quantities from the list
    const productList = JSON.parse(list).map(item => `${item.name} (Kolicina: ${item.quantity})`).join('\n');

    // Create a transporter
    const transporter = nodemailer.createTransport({
        service: 'gmail', // Use your email provider
        auth: {
            user: process.env.EMAIL_USER, // Your email address from .env
            pass: process.env.EMAIL_PASS // Your email password from .env
        }
    });

    // Email options
    const mailOptions = {
        from: 'Sajt',
        to: '[email protected]', // Change this to your recipient email address
        subject: 'New Order',
        text: `Name: ${name || companyName}\nPhone: ${phone}\nAddress: ${address}\nCountry: ${country}\nCity: ${city}\nContact Name: ${contactName || ''}\nDate and Time: ${currentDateTime}\n\nOrder Details:\n${productList}\n\nTotal Price: ${totalPrice}`
    };

    // Send email
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            console.log(error);
            res.status(500).send('Error sending email');
        } else {
            console.log('Email sent: ' + info.response);
            res.status(200).send('success');
        }
    });
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

and my checkout1.js file

Code:
document.querySelectorAll('.form').forEach(form => {
    form.addEventListener('submit', function(e) {
        e.preventDefault();

        // Prvo proveri da li je reCAPTCHA potvrđena
        let captchaResponse = form.querySelector('.g-recaptcha-response').value;

        if (!captchaResponse) {
            alert('Molimo vas da potvrdite da niste robot.');
            return;
        }

        // Prikupi podatke iz forme
        let formData = {};
        new FormData(form).forEach((value, key) => {
            formData[key] = value;
        });
        formData['g-recaptcha-response'] = captchaResponse;

        // Podesi list i totalPrice u zavisnosti od forme
        let listName = form.querySelector('input[name="list"]');
        let totalPriceName = form.querySelector('input[name="totalPrice"]');

        if (listName && totalPriceName) {
            let listCart = JSON.parse(localStorage.getItem('listCart')) || [];
            let totalPrice = calculateTotalPrice(listCart);

            listName.value = JSON.stringify(listCart);
            totalPriceName.value = totalPrice;
        }

        // Kreiraj AJAX zahtev
        let xhr = new XMLHttpRequest();
        xhr.open('POST', '/send-email');
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onreadystatechange = function() {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                if (xhr.status == 200) {
                    // Resetuj korpu i preusmeri na index.html
                    resetCart();
                    window.location.href = '/index.html';
                } else {
                    alert('Došlo je do greške prilikom slanja podataka. Molimo pokušajte ponovo.');
                }
            }
        };
        xhr.send(JSON.stringify(formData));
    });
});

// Funkcija za izračunavanje ukupne cene (primer, implementirajte prema vašim potrebama)
function calculateTotalPrice(listCart) {
    return listCart.reduce((total, item) => total + item.price * item.quantity, 0);
}

// Funkcija za resetovanje korpe
function resetCart() {
    localStorage.removeItem('listCart'); // Uklanja podatke iz localStorage
    listCart = []; // Prazni niz listCart

    // Ažurira HTML da odražava praznu korpu
    addCartToHTML();
}

I try to add a

Code:
<input type="hidden" name="list" id="list1">
<input type="hidden" name="totalPrice" id="totalPrice1">

to my button but all i got is error that coudnt send data at all. Now i can send data with this js but problem is that i need to confirm alert and submit again button. Any suggestions?

<p>i have a problem with sending data to my mail from form.I have a 2 form in my code, one is for "fizickaLica" one is for "pravnaLica". Now i have js code which send data from first form to my mail, but when I want to send data from second form i got my alert that said: "Došlo je do greške prilikom slanja podataka. Molimo pokušajte ponovo."("An error occurred while sending data. Please try again.") What should i do? This is my form</p>
<pre class="lang-html prettyprint-override"><code><div id="fizickaLica" class="tab1 active">
<form class="form" id="checkoutForm">
<div class="group">
<label for="name">Ime</label>
<input type="text" name="name" id="name" required oninvalid="this.setCustomValidity('Unesite ime i prezime')" oninput="this.setCustomValidity('')">
</div>

<div class="group">
<label for="phone">Telefon</label>
<input type="text" name="phone" id="phone" required>
</div>

<div class="group">
<label for="address">Adresa</label>
<input type="text" name="address" id="address" required>
</div>

<div class="group">
<label for="country">Zemlja</label>
<input type="text" name="country" id="country" required>
</div>

<div class="group">
<label for="city">Grad</label>
<input type="text" name="city" id="city" required>
</div>
<div class="g-recaptcha" data-sitekey="6Ldkjf8pAAAAAJ77ZZn3qOnfd17dU0kjN0847L1m"></div>
<button class="buttonCheckout submit" id="checkoutButton" type="submit" action="index.html">Poruči</button><br>
<input type="hidden" name="list" id="list">
<input type="hidden" name="totalPrice" id="totalPrice">
</form>
</div>

<div id="pravnaLica" class="tab1">
<form class="form" id="checkoutFormPravna">
<div class="group">
<label for="companyName">Naziv firme</label>
<input type="text" name="companyName" id="companyName" required>
</div>

<div class="group">
<label for="contactName">Kontakt osoba</label>
<input type="text" name="contactName" id="contactName" required>
</div>

<div class="group">
<label for="phone">Telefon</label>
<input type="text" name="phone" id="phone1" required>
</div>

<div class="group">
<label for="address">Adresa</label>
<input type="text" name="address" id="address1" required>
</div>

<div class="group">
<label for="country">Zemlja</label>
<input type="text" name="country" id="country1" required>
</div>

<div class="group">
<label for="city">Grad</label>
<input type="text" name="city" id="city1" required>
</div><br>
<div class="group">
<input type="checkbox" id="privacyCheck" required>
<label for="privacyCheck">Slažem se sa <a href="pravila-privatnosti.html">pravilom privatnosti</a></label><br>
</div>
<div class="g-recaptcha" data-sitekey="6Ldkjf8pAAAAAJ77ZZn3qOnfd17dU0kjN0847L1m"></div>
<button class="buttonCheckout submit" id="checkoutButton1" type="submit" action="index.html">Poruči</button><br>
<input type="hidden" name="list" id="list1">
<input type="hidden" name="totalPrice" id="totalPrice1">
</form>
</div>
</code></pre>
<p>and I have cuple of js files but for this problem just 2 was importanr my server.js</p>
<pre class="lang-js prettyprint-override"><code>const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const path = require('path');
require('dotenv').config(); // Učitaj .env datoteku

const app = express();
const port = 3000;

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Serve static files from the root directory
app.use(express.static(path.join(__dirname)));

// Serve the 'checkout.html' file as the default page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'checkout.html'));
});

// Endpoint to handle form submission
app.post('/send-email', (req, res) => {
const { name, phone, address, country, city, companyName, contactName, list, totalPrice } = req.body;

const currentDateTime = new Date().toLocaleString();

// Extract product names and quantities from the list
const productList = JSON.parse(list).map(item => `${item.name} (Kolicina: ${item.quantity})`).join('\n');

// Create a transporter
const transporter = nodemailer.createTransport({
service: 'gmail', // Use your email provider
auth: {
user: process.env.EMAIL_USER, // Your email address from .env
pass: process.env.EMAIL_PASS // Your email password from .env
}
});

// Email options
const mailOptions = {
from: 'Sajt',
to: '[email protected]', // Change this to your recipient email address
subject: 'New Order',
text: `Name: ${name || companyName}\nPhone: ${phone}\nAddress: ${address}\nCountry: ${country}\nCity: ${city}\nContact Name: ${contactName || ''}\nDate and Time: ${currentDateTime}\n\nOrder Details:\n${productList}\n\nTotal Price: ${totalPrice}`
};

// Send email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
res.status(500).send('Error sending email');
} else {
console.log('Email sent: ' + info.response);
res.status(200).send('success');
}
});
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
</code></pre>
<p>and my checkout1.js file</p>
<pre><code>document.querySelectorAll('.form').forEach(form => {
form.addEventListener('submit', function(e) {
e.preventDefault();

// Prvo proveri da li je reCAPTCHA potvrđena
let captchaResponse = form.querySelector('.g-recaptcha-response').value;

if (!captchaResponse) {
alert('Molimo vas da potvrdite da niste robot.');
return;
}

// Prikupi podatke iz forme
let formData = {};
new FormData(form).forEach((value, key) => {
formData[key] = value;
});
formData['g-recaptcha-response'] = captchaResponse;

// Podesi list i totalPrice u zavisnosti od forme
let listName = form.querySelector('input[name="list"]');
let totalPriceName = form.querySelector('input[name="totalPrice"]');

if (listName && totalPriceName) {
let listCart = JSON.parse(localStorage.getItem('listCart')) || [];
let totalPrice = calculateTotalPrice(listCart);

listName.value = JSON.stringify(listCart);
totalPriceName.value = totalPrice;
}

// Kreiraj AJAX zahtev
let xhr = new XMLHttpRequest();
xhr.open('POST', '/send-email');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
if (xhr.status == 200) {
// Resetuj korpu i preusmeri na index.html
resetCart();
window.location.href = '/index.html';
} else {
alert('Došlo je do greške prilikom slanja podataka. Molimo pokušajte ponovo.');
}
}
};
xhr.send(JSON.stringify(formData));
});
});

// Funkcija za izračunavanje ukupne cene (primer, implementirajte prema vašim potrebama)
function calculateTotalPrice(listCart) {
return listCart.reduce((total, item) => total + item.price * item.quantity, 0);
}

// Funkcija za resetovanje korpe
function resetCart() {
localStorage.removeItem('listCart'); // Uklanja podatke iz localStorage
listCart = []; // Prazni niz listCart

// Ažurira HTML da odražava praznu korpu
addCartToHTML();
}
</code></pre>
<p>I try to add a</p>
<pre><code><input type="hidden" name="list" id="list1">
<input type="hidden" name="totalPrice" id="totalPrice1">
</code></pre>
<p>to my button but all i got is error that coudnt send data at all. Now i can send data with this js but problem is that i need to confirm alert and submit again button. Any suggestions?</p>
 

Latest posts

I
Replies
0
Views
1
impact christian
I
Top