1

My web app works fine until i press the <button id="button" class="btn btn-primary btn-lg" onclick="sendForm()" value="GENERA XML">GENERA XML</button> when i press it, the web app crash, i've check the debugger it seems like the function post is called two times, the first time the function works perfectly, the second time it runs it make my application crash.

this is the form:

<form class="container broadcast-form" action="/form" enctype="multipart/form-data" method="post">

this is my client side js:

function sendForm() {

const Form = document.querySelector('.broadcast-form')

let formSend = new FormData();

const cliente = Form.querySelector('#clienti').options[clienti.selectedIndex].text

formSend.append('cliente', cliente);

 $.ajax({
      url: '/form',
      method: "POST",
      dataType: 'json',
      data: formSend,
      processData: false,
      contentType: false,
      success: function(result){
        console.log(result);
      },
      error: function(er){
        console.log(er);
      }
    });

}

and this is my server side:

app.post('/form', (req, res) => {
con.query(('SELECT * FROM Tab_Clienti WHERE Cliente = "' + cliente +'"'), (err, QCliente, fields) =>{
    if (err) console.log(err)
    else{...}
    })
})

For obvious reasons i've reduced the code with only the essential.

How do I let the application send the form just one time?

This is the missing part:

 const cliente = Form.querySelector('#clienti').options[clienti.selectedIndex].text
const emittente = Form.querySelector('#emittenti').options[emittenti.selectedIndex].text
const inputFile = Form.querySelector('#path').value.replace(/.*[\/\\]/, '')
const dataT =     Form.querySelector('#date').value
const oraTrasmissione = Form.querySelector('#timeTransmission').value
const sottotitolo = Form.querySelector('#sottotitolo').value
const titoloTrasmissione = Form.querySelector('#titoloTrasmissione').value
const presentatore = Form.querySelector('#presentatore').value
const sommario = Form.querySelector('#sommario').value
const keyword = Form.querySelector('#keyword').value
const currentDate = new Date().toLocaleDateString()
const currentTime = new Date().toLocaleTimeString();
const durataTrasmissione = Math.floor(Form.querySelector('#preview').duration);
const fileVideo = Form.querySelector('#preview').src


formSend.append('cliente', cliente);
formSend.append("inputFile",Form.querySelector('#path').value.replace(/.*[\/\\]/, ''));
formSend.append('emittente', emittente);
formSend.append('sottotitolo',sottotitolo);
formSend.append('dataT', dataT);
formSend.append('currentDate', currentDate);
formSend.append('currentTime', currentTime);
formSend.append('oraTrasmissione', oraTrasmissione);
formSend.append('durataTrasmissione', durataTrasmissione);
formSend.append('titoloTrasmissione', titoloTrasmissione);
formSend.append('presentatore', presentatore);
formSend.append('sommario', sommario);
formSend.append('keyword', keyword);
formSend.append('fileVideo', Form.querySelector('#preview').src);

and server side:

app.post('/form', upload.single('fileVideo'),(req, res) => {

    var date = new Date(),
    blockid = (date.toJSON().replace(/[\-T:.Z]/g, ''));
    cliente = req.body.cliente
    inputFile = req.body.inputFile
    dataT = req.body.dataT
    currentDate = req.body.currentDate
    currentTime = req.body.currentTime
    oraTrasmissione = req.body.oraTrasmissione
    durataTrasmissione = req.body.durataTrasmissione
    emittente = req.body.emittente
    sottotitolo = req.body.sottotitolo
    titoloTrasmissione = req.body.titoloTrasmissione
    presentatore = req.body.presentatore
    sommario = req.body.sommario
    keyword = req.body.keyword
    fileVideo = req.body.fileVideo
    blockdate = JSON.stringify(date.getFullYear()) + "-" + JSON.stringify(date.getMonth()+1) + "-" + JSON.stringify(date.getDate()) + " " + JSON.stringify(date.getHours()) + ":" + JSON.stringify(date.getMinutes()) + ":" + JSON.stringify(date.getSeconds())

    con.query(('INSERT INTO movedb.Tab_Invii (Data_Invio, Orario_Invio, Nome_File_Inviato, Cliente, Emittente, Orario_trasmissione, Durata_trasmissione, Nome_trasmissione, Titolo_Trasmissione, Presentatore, Keyword) VALUES ("' + currentDate + '","' + currentTime + '","' + inputFile + '","' + cliente + '","' + emittente + '","' + oraTrasmissione + '","' + durataTrasmissione + '","'+ sottotitolo + '","' + titoloTrasmissione + '","' + presentatore + '","'  + keyword +'");'), (err, req, res)=>{
      if (err) console.log(err)
      else{
    con.query(('SELECT * FROM Tab_Clienti WHERE Cliente = "' + cliente +'"'), (err, QCliente, fields) =>{
    if (err) console.log(err)
    else{

    con.query(('SELECT * FROM Tab_Emittenti WHERE  Emittente = "' + emittente +'"'), (err, QEmittente, fields) =>{

      if (QEmittente[0].Media == 'TV') var mediaEmittente = 'T';
      if (QEmittente[0].Media == 'Radio') var mediaEmittente = 'R';
      if (QEmittente[0].Media == 'W') var mediaEmittente = 'W';
Gargantua
  • 288
  • 2
  • 4
  • 15

3 Answers3

1

Try like below

$('.broadcast-form').unbind('submit').submit();

or

('.broadcast-form').submit(function(e){
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: $(this).attr( 'action' ),
            data: $(this).serialize(),
              success: function( response ) {

            }
        });

        return false;
    });
PPL
  • 5,800
  • 1
  • 8
  • 27
0

The problem is that both:

<form class="container broadcast-form" action="/form" enctype="multipart/form-data" method="post">

AND

$.ajax({
  url: '/form',
  method: "POST",
  dataType: 'json',
  data: formSend,
  processData: false,
  contentType: false,
  success: function(result){
    console.log(result);
  },
  error: function(er){
    console.log(er);
  }
});

They Were sending the same form to the same "post" call, so one of them get the data and the other one not so the other one return an error. The solution is to let one of them address the call to another "post".

Gargantua
  • 288
  • 2
  • 4
  • 15
-1

You should try to remove action in your code to have something like this:

<form class="container broadcast-form"
enctype="multipart/form-data" method="post">

Then in the sendForm() function pass e and add e.preventdefault() in your function.

TheBlackBenzKid
  • 24,177
  • 36
  • 128
  • 199
JKRuigu
  • 1
  • 2