reload html table on form submit - javascript

I have a form that when submitted shows a table with different data (ajax request to php file) depending on the user's input. Is there a way for me to dynamically reload the table with new information each time the user submits the form? As of now, the data keeps appending to the table after each submit and keeps adding on to the last submit data. Any suggestions would be greatly appreciated, thanks!
HTML
<form id = "infoForm"
action="file.php" method="post">
<b>Enter info:</b> <input type = "text" name = "info"
id = "infoInput" maxlength = "10" required >
<button type = "submit" id = "submit_form">Submit</button>
</form>
<table id = "infoTable">
<tbody>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</tbody>
</table>
JavaScript
$("#infoForm").submit(function() {
$("#infoTable").fadeIn(400);
//InputData is an array that contains the user input data
$.post( "file.php", InputData,
function( data ){
var names = data.names; //from PHP file
var numbers = data.numbers; //from PHP file
var namesArray = names.split(',');
var numbersArray = numbers.split(',');
for(var i = 0; i < namesArray.length; i++) {
$("#infoTable > tbody").append('<tr><td>'+namesArray[i]+'</td><td>'+numbersArray[i]+'</td></tr>');
}
}, "json");
return false;
});

You need to clean the tbody then append the new records.
Try this:
$("#infoForm").submit(function() {
$("#infoTable").fadeIn(400);
//InputData is an array that contains the user input data
$.post( "file.php", InputData,
function( data ){
var names = data.names; //from PHP file
var numbers = data.numbers; //from PHP file
var namesArray = names.split(',');
var numbersArray = numbers.split(',');
$("#infoTable > tbody").empty(); // clean the tbody before adding new data
for(var i = 0; i < namesArray.length; i++) {
$("#infoTable > tbody").append('<tr><td>'+namesArray[i]+'</td><td>'+numbersArray[i]+'</td></tr>');
}
}, "json");
return false;
});

Related

Show data in ajax table, jsp and servlets

I have the following case that I am having a hard time solving.
In the image what I try to do is look for the documents of the selected process and that they are displayed in the table.
This is done with ajax, jsp and servlet.
For the select dropdown, this is the code where I list the processes through java and jsp classes.
<select class="form-control js-example-basic-single" name="sucursal">
<%
MantenedorProcesosLMD md = new MantenedorProcesosLMD();
List<procesoslmd> ld = md.listar_proc_lista(con);
for (procesoslmd p : ld) {
%>
<option value="<%=p.getLDM_ID()%>">
<%=p.getLDM_NOMBPROCESOS()%>
</option>
<%
}
%>
</select>
This is my code in sql where by means of the IDPROCESOS parameter I look for the documents.
SELECT
D.IDLDMDOCUMENTOS,
LT.NOMBRETIPO,RTRIM(D.LDM_NOMENCLATURA) AS NOMENCLATURA,
RTRIM(D.LDM_NOMBRE_DOCUMENTO) AS TITULO,
D.LDM_FECHA_SUBIDA,D.LMD_RUTA_DOCUMENTO
FROM LDM_DOCUMENTOS_ D
LEFT JOIN LDM_PROCESOS_ LP ON LP.IDLDMPROCESOS = D.IDLDMPROCESOS
LEFT JOIN LDM_TIPO_DOCUMENTO_ LT ON LT.IDTIPODOC = D.IDTIPODOC
WHERE LP.IDLDMPROCESOS = #IDLDMPROCESOS
But so far I can't get to the code to find the documents by clicking the search button, I'm trying to do it with ajax I'm still collecting information.
implement this ajax code where I get the value of my select dropdown the IDPROCESOS and if it brings me the documents so far I can show it in the console, but I want to add it to the table but when I click on the search button
$(document).ready(function () {
$('select[name=procesoldm]').on('change', function () {
$.ajax({
type: 'GET',
url: '../sv_proxdocumento',
data: 'codigoproceso='+$('select[name=procesoldm]').val(),
statusCode: {
404: function () {
alert('PAGINA NO ENCONTRADA');
},
500: function () {
alert('ERROR EN EL SERVIDOR');
}
},
success: function (dados) {
var pegadatos = dados.split(":");
console.log(pegadatos);
for (var i = 0; i < pegadatos.length -1; i++){
var codigodocumento = pegadatos[i].split("-")[0];
var nombretipo = pegadatos[i].split("-")[1];
console.log(nombretipo);
}
}
});
})
});
How do I pass that found data to a table with ajax, thanks for your time.
how it should look in the table when clicking the search button
You can use another for-loop after spliting your values and then on each iteration append td inside some variable using += and then add this generated html inside your table.
Demo Code :
$(document).ready(function() {
/*$('select[name=procesoldm]').on('change', function() {
$.ajax({
//other codes..
success: function(dados) {*/
//var pegadatos = dados.split(":");
//just for demo
var pegadatos = ["1-abc-abd-abdd-2/1/12", "2-abc2-abd2-abdd2-2/22/12", ""]
var html = ""; //declare this
//loop through main array
for (var i = 0; i < pegadatos.length - 1; i++) {
var values = pegadatos[i].split("-") //split values
html += `<tr>`
for (var j = 0; j < values.length; j++) {
html += `<td>${values[j]}</td>` //splited values..
}
html += `<td>--Visitor--</td>`
html += `</tr>`
}
$("table tbody").html(html) //add result inside tbody
/* }
});
})*/
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th>No</th>
<th>DocumentType</th>
<th>DocumentNaming</th>
<th>title</th>
<th>date</th>
<th>visitor</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Setting default values to appended text boxes using jQuery

I am looking to pass a list of autocomplete values to text boxes that have been appended based on a specified number of units.
function getUnits() {
var units = $("#units").val();
if (units > 1){
for (var count = 1; count < units-1; count++) {
$("<input type='text' /><br>").appendTo("#left-col");
}
$("#left-col").append('<input type="text">');
}}
$(function() {
google.script.run.withSuccessHandler(buildTagList)
.getAvailableTags();
});
function buildTagList(availableTags) {
$( '#med' ).autocomplete({
source: availableTags
});
}
This is the code for appending the appropriate amount of text boxes based on the # of units.
function getAvailableTags() {
var ss = SpreadsheetApp.openById("someID");
var s = ss.getSheetByName("someSheet");
var drug = s.getRange("A2:A").getValues();
var headers = 1;
var tagColumn = 0;
var availableTags = [];
for (var row=headers; row < drug.length; row++) {
availableTags.push(drug[row][tagColumn]);
}
return( availableTags );
}
I have tried creating the appended values with the same name/id/and class, but nothing seems to be working. A bonus question would also be: when a user goes to submit the form, how do I capture all of the appended boxes' values?
Here's a short example of adding textboxes to a dialog and submitting the data back to a spreadsheet
Run addTextBoxestoADialog(). Give it the names of the textboxes separated by forward slash. Like this: name1/name2/name3 and then it will build the form. You can fill in the values and hit submit and the names and values will be appended to the active sheet.
Code.gs:
function addTextBoxestoADialog() {
var ss=SpreadsheetApp.getActive();
var ui=SpreadsheetApp.getUi();
var resp=ui.prompt("Adding Text Boxes to a Dialog","Enter unique names of text boxes separate by forward slash /.",ui.ButtonSet.OK );
var tA=resp.getResponseText().split('/');
var html='<html><head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"><script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>';
html+='<script>function fileUploadJs(frmData){google.script.run.upLoadForm(frmData);}</script></head><body>';
html+='<form id="myForm">';
for(var i=0;i<tA.length;i++) {
html+=Utilities.formatString('<br /><input type="text" value="%s" name="%s" /> %s',i+1,tA[i],tA[i]);//added default values
}
html+=Utilities.formatString('<input type="hidden" value="%s" name="NameArray" />',tA.join('~~~'));
html+='<br /><input type="button" value="Submit" onclick="fileUploadJs(this.parentNode)" />';
html+='</form></body></html>';
var userInterface=HtmlService.createHtmlOutput(html);
ui.showModelessDialog(userInterface, "Adding TextBoxes");
}
function upLoadForm(theForm) {
Logger.log(JSON.stringify(theForm));
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var nA=theForm.NameArray.split('~~~');
for(var i=0;i<nA.length;i++) {
sh.appendRow([nA[i],theForm[nA[i]]]);
}
}

Get data sent from form in popup

I need to Get data sent from form in popup but the problem that in the form there is many checkboxes with same name like name='list[]' :
JS :
function showPopup(){
var user = document.getElementById("check").value;
var popup = window.open("milestone.php?a="+user,"hhhhhh","width=440,height=300,top=100,left=‌​300,location=1,status=1,scrollbars=1,resizable=1") ;
}
html :
<input type='checkbox' name="approve[]" value="get from Mysql">
<input type='checkbox' name="approve[]" value="get from Mysql">
<input type='checkbox' name="approve[]" value="get from Mysql">
var user = document.getElementById("check").value;
That won't work because:
You need to get multiple values
You need to get the values only of checkboxes that have been checked
You don't have an element with that id (but an id has to be unique anyway)
The fields all have the same name. Use the name.
var inputs = document.getElementsByName("approve[]")
Then you need to generate your form data from it, filtering out the ones which are not checked:
var form_data = [];
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if (input.checked) {
form_data.push(encodeURIComponent(input.name) + "=" + encodeURIComponent(input.value));
}
}
Then put all the form data together:
var form_data_query_string = form_data.join("&");
Then put it in your URL:
var url = "milestone.php" + "?" + form_data_query_string;
Then open the new window:
var popup = window.open(url,"hhhhhh","width=440,height=300,top=100,left=‌​300,location=1,status=1,scrollbars=1,resizable=1") ;
If you want to pass the array via get you should loop through all the checked checkboxes and store the value of everyone in array then convert them to Json using JSON.stringify so you can passe them in url :
function showPopup(){
var approve_array=[];
var checked_checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
for(var i=0;i<all_checkboxes.length;i++){
approve_array[i] = checked_checkboxes[i].value;
}
var url = "milestone.php?approve="+JSON.stringify(approve_array);
var popup = window.open(url,"hhhhhh","width=440,height=300,top=100,left=‌​300,location=1,status=1,scrollbars=1,resizable=1") ;
}
In you php page you could get the array passed as Json using json_decode :
$array_of_approves = json_decode($_GET['approve']);
Hope this helps.
You can access the value as:
$approveList= $_POST['approve'];
and can be iterated as
foreach ($approveList as $approve){
echo $approve."<br />";
}

After prepend, set value as input javascript then process values in php script

I am using script to print selected values from table into another div.
<script>
$(".addValues").click(function () {
$('#selection').show();
var $this = $(this),
myCol = $this.closest("td"),
myRow = myCol.closest("tr"),
targetArea = $("#selection");
var qte_input = ('<input type="text" name="kolicina" id="kolicina" placeholder="kg / m" size="10"/>');
var broj = ($("td.data-id", myRow).text());
targetArea.prepend(broj + qte_input +"<hr />");
var arr = { sifra:broj, kolicina:qte_input };
$.ajax({
url: 'script.php',
data: arr,
type: 'post',
});
});
</script>
I am trying to get selected values in script.php, multiple values will be selected and after each selection I need to type quantity that is var qte_input.
Could anyone tell me how to set var broj as input and in the same time print it to another div as selected?
html code
<table id="datatable" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>-</th>
</tr>
</thead>
<tbody>
<?php while($r=$q->fetch()){ ?>
<tr>
<td class='data-id'><?=''. $r['Id']?> </td>
<td> <button class="addValues" value="<?=''. $r['Id']?>"><i class="ion-ios-cart-outline"></button></td>
</tr>
<?php } ?>
</tbody>
</table>
Once I click on button one value prints in div. Multiple values could be selected as displayed on the image. Once I finish selection I hit button "Pošalji zahtjev" it should pick up all
You should write a function which collect you all data from the table. After that this collection should be sent to you backend via ajax. Demo in this fiddle: https://jsfiddle.net/mgrem9gb/
/**
* Function collect the form data
*/
function collectData(container){
var data = [];
$(container).find('tbody').find('tr').each(function(index, item){
var rowData = {
id: $(item).find('td.data-id').text(),
value: $(item).find('input[name="kolicina"]').val()
};
data.push(rowData);
});
return data;
}
/**
* Excecute the data collect function and the ajax post
*/
$.ajax({
url: 'script.php',
data: collectData('#datatable'),
type: 'post',
});

Submit form without reloading page [duplicate]

This question already has answers here:
Submit form without page reloading
(19 answers)
Closed 9 years ago.
I have a function built in JavaScript that I want to be executed after a form submit is hit. It basically changes the look of the page completely. But I need a variable from the search box to still go through to the JavaScript. At the moment it flashes and resets what was there because it reloads the page.
So I set up a return false in my function which keeps it from doing that but the variable I want doesn't get submitted through the form. Any ideas on what I should do to get it? It's okay for the page to refresh as long as the updateTable() function works and isn't reset by the page reset.
<form action="" method="get" onsubmit="return updateTable();">
<input name="search" type="text">
<input type="submit" value="Search" >
</form>
This is the updateTable function:
function updateTable() {
var photoViewer = document.getElementById('photoViewer');
var photo = document.getElementById('photo1').href;
var numOfPics = 5;
var columns = 3;
var rows = Math.ceil(numOfPics/columns);
var content="";
var count=0;
content = "<table class='photoViewer' id='photoViewer'>";
for (r = 0; r < rows; r++) {
content +="<tr>";
for (c = 0; c < columns; c++) {
count++;
if(count == numOfPics) break; // check if number of cells is equal number of pictures to stop
content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
}
content +="</tr>";
}
content += "</table>";
photoViewer.innerHTML = content;
}
You can't do this using forms the normal way. Instead, you want to use AJAX.
A sample function that will submit the data and alert the page response.
function submitForm() {
var http = new XMLHttpRequest();
http.open("POST", "<<whereverTheFormIsGoing>>", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
You can use jQuery serialize function along with get/post as follows:
$.get('server.php?' + $('#theForm').serialize())
$.post('server.php', $('#theform').serialize())
jQuery Serialize Documentation: http://api.jquery.com/serialize/
Simple AJAX submit using jQuery:
// this is the id of the submit button
$("#submitButtonId").click(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
I guess this is what you need. Try this .
<form action="" method="get">
<input name="search" type="text">
<input type="button" value="Search" onclick="return updateTable();">
</form>
and your javascript code is the same
function updateTable()
{
var photoViewer = document.getElementById('photoViewer');
var photo = document.getElementById('photo1').href;
var numOfPics = 5;
var columns = 3;
var rows = Math.ceil(numOfPics/columns);
var content="";
var count=0;
content = "<table class='photoViewer' id='photoViewer'>";
for (r = 0; r < rows; r++) {
content +="<tr>";
for (c = 0; c < columns; c++) {
count++;
if(count == numOfPics)break; // here is check if number of cells equal Number of Pictures to stop
content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
}
content +="</tr>";
}
content += "</table>";
photoViewer.innerHTML = content;
}
I did it a different way to what I was wanting to do...gave me the result I needed. I chose not to submit the form, rather just get the value of the text field and use it in the javascript and then reset the text field. Sorry if I bothered anyone with this question.
Basically just did this:
var search = document.getElementById('search').value;
document.getElementById('search').value = "";

Categories

Resources