I am submitting a form when user clicks on submit button using JQuery. But upon clicking it submits same form multiple times and I've no clue why is this happening. Tried lots of things but failed. Below is the code.
I am adding my PHP, Javascript and HTML code below.
HTML:
<div class="box-body big">
<form id="pdf-generator" action="<?= $this->base; ?>/companies/generatePdf/" method="post" target="_blank">
<select id="pdfname" class="form-control" name="pdfname">
<option value="showfields">---Show Available Fields---</option>
<option value="29300____test1.pdf">29300____test1.pdf</option>
</select>
<input type="hidden" name="fieldPairs" id="fieldPairs" value="" />
</form>
<div class="divide-12"></div>
<button id="genPdfFormButton" type="button" class="btn btn-success pull-right">Generate PDF</button>
<div class="divide-12"></div>
</div>
JS:
$('#genPdfFormButton').click(function(){
var elements = document.getElementsByTagName("input");
var textAreas = document.getElementsByTagName("textarea");
var list = "";
var pair = "";
document.getElementById("fieldPairs").value = '';
//all input fields
for (var i=0; i<elements.length; i++) {
pair = elements[i].id + "=" + elements[i].value;
list = (list.length == 0) ? pair : list + "|" + pair;
}
//all textareas
for (var i=0; i<textAreas.length; i++) {
pair = textAreas[i].id + "=" + textAreas[i].value;
list = (list.length == 0) ? pair : list + "|" + pair;
}
document.getElementById("fieldPairs").value = list;
$('#pdf-generator').submit();
});
PHP:
public function generatePdf() {
$this->log("==>===============[start]=====================", 'debug');
$this->autoRender = false;
$pdfName = $this->request->data['pdfname'];
//get the submitted data
$formData = $this->processFormData($this->request->data['fieldPairs']);
if($pdfName == "showfields") { //show only form data fields
var_dump($formData);
} else { //generate PDF file
$this->log("==> gonna call generatePdf <== ", 'debug');
$pdf = new PdfForm(PDF.$pdfName, $formData);
$pdf->download();
}
}
When this code calls the php function, I can see same logs messages multiple times because the function is being called multiple time.
p.s: This issues is not due to clicking on submit button multiple times.
vendor/cakephp/cakephp/VERSION.txtorlib/Cake/VERSION.txt) - thanks!