I am getting data as form of Java Bean and I am inserting each value into a table.
Values are retrieved as common way at first.
But I added some Javascript source, so that I can modify the value if I click any area near it.
Now I would like to save the data in database as well if there was any change after I modify.
How can I do that?
Here is my HTML code
<table class="bg-light table table-hover" style="overflow:hidden">
<th>Word</th>
<th>Dialogue</th>
<th>Practice</th>
<c:forEach items="${list}" var="engboardVO">
<tr>
<td data-editable>${engboardVO.word}</td>
<td data-editable>${engboardVO.dialogue}</td>
<td data-editable>${engboardVO.practice}</td>
</tr>
</c:forEach>
</table>
And Javascript
$("body").on("click", "[data-editable]", function() {
var $el = $(this);
/* var $input = $('<input style="width:500px; height:100px"/>').val( $el.text() ); */
var $input = $('<textarea rows=5 style="width:500px"/>').val($el.text());
$el.replaceWith($input);
var save = function() {
var $td = $("<td data-editable />").text($input.val());
$input.replaceWith($td);
};
$($input).blur(function() {
save();
})
});
You can use ajax for submitting data without form.
I can see you are using jQuery library. So I am writing code based on this library.
In HTML:
<table class="bg-light table table-hover" style="overflow:hidden">
<th>Word</th>
<th>Dialogue</th>
<th>Practice</th>
<c:forEach items="${list}" var="engboardVO">
<tr>
<td data-name="word" data-editable>${engboardVO.word}</td>
<td data-name="dialogue" data-editable>${engboardVO.dialogue}</td>
<td data-name="practice" data-editable>${engboardVO.practice}</td>
</tr>
</c:forEach>
</table>
In javascript:
$("body").on("click", "[data-editable]", function() {
var $el = $(this);
var $input = $('<textarea rows=5 style="width:500px"/>').val($el.text());
$el.html($input);
var field_name = $el.attr('data-name');
var save = function() {
var $val= $input.val();
$.ajax({
type: "POST",
url: "update-url",
data: {fieldname: field_name, fieldvalue:$input.val()},
dataType: "json",
success: function(msg) {
// do something on success
$el.html($val);
},
error: function(msg){
// do something on error
}
});
};
$($input).blur(function() {
save();
})
});
Then in server side, you can save fieldvalue as value of fieldname in your database.
Basically what we are doing here is:
Added an attribute data-name in td tag, its value can be related to your field name in table.
Get the name of attribute in javascript using var field_name = $el.attr('data-name');.
Using post request in ajax call passed the field_name and and value of this field to server.
$.ajax({
type: "POST",
url: "update-url",
data: {fieldname: field_name, fieldvalue:$input.val()},
dataType: "json",
success: function(msg) {
// do something on success
$el.html($val);
},
error: function(msg){
// do something on error
}
});
Now in server side, you need to fetch this data as you fetch normally for post request in submit of a form and save this data in database.
url is same as action you provide in form tag.
Edit:
Check now. You were replacing the td, whereas you had to replace html inside td.
Don't worry if you don't have a form or can't have it for some reasons
You can still read the inputs of your web page and use them or send them to the server.
See below a simple example:
var inputs = document.getElementsByTagName('input');
var data = []
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
data.push(inputs[index].value)
}
var json = JSON2.stringify(data);
$.ajax({
type: "POST",
url: "your-api-url",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// done code
}
});
Related
Im trying to pre populate an input text box in a modal. Currently i click the edit button which calls a jQuery function that makes an ajax call
<script>
$(document).ready(function(){
$(".selectRow").click(function(e)
{
e.preventDefault();
var row = $(this).closest("tr"),
tds = row.find("td:nth-child(1)").first();
var textval = tds.text();
$.ajax({
url: "EditApplication?handler=GetRowInfo",
type: "POST",
dataType: "json",
data: { textval },
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function () {
alert("success");
},
complete: function () {
$('#editAppModal').modal('show');
},
failure: function () {
alert("failure");
}
})
});
});
</script>
On completion i show the modal. This jQuery function calls a method in the code behind called GetRowInfo which grabs a cell from a table.
GetRowInfo
public void OnPostGetRowInfo(string textval)
{
Console.WriteLine("-----------------"+textval);
DutyWeb dutyWebManager = new DutyWeb();
textval = textval.Trim();
Console.WriteLine("-----------------NEW-"+textval);
selectedRow = dutyWebManager.SearchByApplication(textval);
ViewData["appName"] = textval;
}
I assign the text value sent into the ViewData as appName
I then assign the textbox input value to be the ViewData["appName"
<div class="modal-body">
<input type="text" name="appName" id="appName" value='#ViewData["appName"]'>
<input type="text" name="appShortName" style="width:15%">
<br>
</div>
I dont know if im doing this wrong but it seems right to me. The modal is inside of a form element. Stepping through revealed that the ViewData is indeed storing the correct value, but its not being displayed in the textbox
I would like to avoid using jQuery to do this. I feel like ViewData is a much easier way of accomplishing the same task
I have a form, when I submit it it creates an ajax function and then creates a table out of the data in the success. But knowing that my page is dynamic (without reloading the page I call the ajax function many times), but each time the data in the success doesn't get removed before generating more data. Is that normal? How can I empty the success data variable before sending the ajax?
Function :
function submitForm() {
if ($.fn.DataTable.isDataTable("#table")) {
$('#table').DataTable().clear();
$('#table').DataTable().destroy();
$('#table').empty();
}
url = $("#form").serialize();
console.log(url);
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: '/api/test?'+url,
'beforeSend': function (request) {
data = {}; // like this maybe?
},
success: function (data) {
//Getting data variable containing
data = data.data;
//the second time I call the function, data contains the new and old stuff at the same time
}
});
}
Form :
<form method="GET" action="" class="form-horizontal" id="form" onsubmit="return false;">
<button type="submit" onclick="submitForm();">Update table</button>
</form>
Table :
<table class="table table-striped display nowrap col-md-12" id="achats_table">
<thead>
<tr style="border-bottom:2px dashed #ccc"></tr>
</thead>
<tbody></tbody>
<tfoot align="right">
<tr></tr>
</tfoot>
</table>
You have to empty the table in beforeSend,
function submitForm() {
url = $("#form").serialize();
console.log(url);
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: '/api/test?'+url,
'beforeSend': function (request) {
if ($.fn.DataTable.isDataTable("#achats_table")) {
$('#table').DataTable().clear();
$('#table').DataTable().destroy();
$('#table').empty();
}
},
success: function (data) {
//Getting data variable containing
data = data.data;
//the second time I call the function, data contains the new and old stuff at the same time
}
});
}
I am trying to fetch data from a table and push the selected data to my server.
I have tried selecting columns from my table then making an HTTP request, but it didn't work.
Can anyone help me?
This is my understanding
here is a procedure if you like to do
insert all you desire record set into an array
make a json using json_encode() method of php.
use curl post request and pass the json string
Here's an example of how to pull data from a HTML table, put it into a javascript array, convert it to json and send it to the server
https://jsfiddle.net/f958qokn/
<table id="MyTable">
<tr>
<td>1</td>
<td>Code Monkey</td>
</tr>
<tr>
<td>2</td>
<td>Code Elephpant</td>
</tr>
</table>
<input id="PostTableData" type="button" value="Post Table Data"/>
<script type="text/javascript">
$(document).ready(function() {
$( "#PostTableData" ).on( "click", function() {
var TableData = [];
$("#MyTable tr").each(function() {
var RowData = [];
var ColumnsData = $(this).find('td');
if (ColumnsData.length > 0) {
ColumnsData.each(function() { RowData.push($(this).text()); });
TableData.push(RowData);
}
});
alert(JSON.stringify(TableData));
jQuery.ajax({
type: 'POST',
url: "/SaveData.php",
data: JSON.stringify(TableData),
dataType: "json",
success: function(data){ alert(data); }
});
});
});
</script>
The problem that I'm facing is that I'm getting an Undefined Index variable while calling Ajax.
I need to post "json" data to the "update.php" page on click of submit button. Basically, I need to capture the values in textbox and send it to the database.
so, I have created a form on the submit button, for which the code is below:
<form action="update.php" method = "post" class="form-inline">
<input type="submit" class="btn btn-info" id = "saveEdits" disabled = "disabled" onclick = "updateVal()" name="saveEdits" value="Update"/>
/form>
This submit button Calls for an UpdateVal function that captures the value on the text-boxes shown on the page and using AJAX send it to the another php page.
updateVal function is as below:
function updateVal() {
var node_list = document.getElementsByTagName('input');
var c = 0;
var fieldName = [];
var fieldText = []
var ID = [];
for (var i = 0; i < node_list.length; i++) {
var node = node_list[i];
if (node.getAttribute('type') == 'text') {
fieldName[c] = node.name;
fieldText[c] = node.value;
ID[c] = node.id;
c++;
}
}
var postData = {
fieldName: fieldName,
fieldText: fieldText,
ID: ID
};
$.ajax({
type: "post",
url: "update.php",
dataType: "json",
data: {'postData' : JSON.stringify(postData)},
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
});
The run time data i.e value in textboxes is being captured and can be shown at console, however, when I'm posting this data on update.php, where I would be capturing the json and will update the database, I'm getting the error:
Notice: Undefined index: in update.php on line 11
Below is my update.php
<?php
$json = $_POST["postData"];
$result = json_decode($json);
var_dump($result);?>
Remove your action attribute from your form, since you send your data per Javascript/AJAX you don't need it.
What you do now is: you send the data twice, once per updateVal() and once per default submit handling of the form.
Since the form-submitted data doesn't contain a input named postData, you are getting your undefined index error.
Edit:
You stated you are not comfortable with the whole AJAX topic. Here is a nice simple answer covering the basics.
Edit2:
to listen for the response of your server add a callback to your ajax-request:
$.ajax({
type: "post",
url: "update.php",
dataType: "json",
data: {'postData' : postData},
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
}).done(function (response, textStatus, jqXHR){
// Show an alert on response
alert(response);
});
I am having a table in which data is being populated through the database.Now what i want is that as soon as i click on one of the row a alert message displays and the READSTATUS of that row become true in my database that is database gets updated .
Now my problem is where to write the code for updating the database as i dont want to move to a different page to do so.
Like my table is something like this :
<input type=hidden name="notifyidd" id="notifyidd" value="<%=messageid%>"/>
<tr bgcolor="#5D1B90" color="#FFFFFF" onmouseover="ChangeColor(this, true,false);" onmouseout="ChangeColor(this, false,false);" onclick="DoNav('shownotification.jsp?mid=<%=messageid%>');">
<td><input type="checkbox" name="" onclick="DoRemove(event);" width="20" class="select_all_mail" value=<%=messageid%>></td>
<td callspan="3" width="1000px"><%=messagesubject%> at <%=sendingtime%></td>
</tr>
and in onclick method of each row i had called the alert.But how to update the database now ?
function DoNav(theUrl)
{
var tt = document.myinbox.notifyidd.value;
alert(tt);
//document.location.href = theUrl;
}
As if i uncomment this line then it will move to next page.But i want to do it on same page only.Please help
EDIT :
I wrote a ajax code to do it.But it gives error.Please help
$(document).ready(function() {
$('#myrow').click(function ()
{
$.ajax({
type: "post",
url: "shownotification.jsp", //this is my servlet
data: {
notifyidd: $('#notifyidd').val()
},
success: function(msg){
if(msg == "success")
alert('Data updated.');
}
});
});
});
Here i assign myrow as id to my table row.Also i removed doNav function now
My error image clicked :
http://postimg.org/image/vix1vzvq5/
Though the error is resolved but this ajax call is not functioning.For test i make my shownotification.jsp as :
<body>
<% String notifyid = request.getParameter("notifyidd");%>
success
</body>
The error message says the server-side code is failing when looking for the attribute "groupid". The post you are sending has notifyidd instead. The server code has no way of knowing if this should map to groupid or not.
Try this. If it doesn't work, update us with the error.
$(document).ready(function() {
$('#myrow').click(function ()
{
$.ajax({
type: "post",
url: "shownotification.jsp", //this is my servlet
data: {
groupid: $('#notifyidd').val()
},
success: function(msg){
if(msg == "success")
alert('Data updated.');
}
});
});
});