Add data to a table row using Ajax - java

I need to add data to a table from a java script. Tha table is in the same .jsp file but no inside the script.
AJAX call
<script type="text/javascript">
function searchDetails() {
$.ajax({
type : "post",
data : {
'accountNo' : $(accNumber).val()
},
url : "/banking-internet/account-history/add",
cache : false,
success : function(data) {
var transactionList = data;
},
error : function(e) {
alert('Error: ' + e);
}
});
}
</script>
Table
<tr>
<th>Transaction Type</th>
<th>Amount</th>
<th class="hide-on-mobile">Description</th>
</tr>
<c:forEach var="transaction" items="${transactionList}">
<tr>
<td>${transaction.transactionDate}</td>
<td>${transaction.transactionType}</td>
<td>${transaction.accountNarration}</td>
</tr>
</c:forEach>
values passed to the data correctly. But I can;t seem to have getthe value outside from the script and use it.
success : function(data) {
var transactionList = data;
},
this part get the value from controller correctly.
Please Help

Add an ID for your table like:
<table id="test_table">
Then call this:
success : function(data) {
var transactionList = data;
addRow ("test_table", transactionList);
},
Finally replace cellX.innerHtml = data.whatever_member_object;
<script language="javascript">
function addRow(tableID, data) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
cell1.innerHtml = data;
var cell2 = row.insertCell(1);
cell2.innerHTML = data;
var cell3 = row.insertCell(2);
cell3.innerHTML = data;
}
</script>
Hope it works.

Related

JSP Multiple Buttons with Different API in Single Form

I was having some problem when trying to put multiple buttons in one JSP form.
<form:form action="/search" method="POST">
<tr>
<td align="left">
<input type="button" onclick="valSubmit('doImageExtractSearchList', this.form);" value="Image Extract" />
</td>
<td align="right">
<input type="button" onclick="valSubmit('doCardIssueSearchList', this.form);" value="Card Search" />
</td>
</tr>
</form:form>
In my controller class, how can I differentiate it comes from which button and specify the API?
#RequestMapping(value = "/search", method = { RequestMethod.POST })
public String doSubmit() {
return "";
}
#RequestMapping(value = "/imageExtract", method = { RequestMethod.POST })
public String doSubmit() {
return "";
}
#RequestMapping(value = "/cardSearch", method = { RequestMethod.POST })
public String doSubmit() {
return "";
}
Thanks!
Since you already trigger a function call on click , why don't you use the function to make an Ajax call to the backend api . That way you could provide separate url for the POST call depending upon the parameter passed into the jquery method like :
function valSubmit(value, form) {
var url;
if(value == "doImageExtractSearchList") {
url = "http://something/search/imageExtract";
}
else if(value == "doCardIssueSearchList") {
url = "http://something/search/cardExtract";
}
var form = $('#formId');
var data = form.serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result) {
alert('ok');
},
error: function(result) {
alert('error');
}
});
}

Data is not loaded in to Datatable using Jsp Ajex crud

i am creating simple crud system.i am beginner of jsp.i can add data into the database using ajax in JSP record added successfully.after add the record i tried to load the data on datatable but data is not loading on datatable
i written code below. what i tried so far
Table
<table id="tbl-projects" class="table table-responsive table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</table>
********JQuery********
<Script>
get_all();
function get_all()
{
$('#tbl-projects').dataTable().fnDestroy();
$.ajax({
url : "all_project.jsp",
type : "GET",
dataType : "JSON",
success:function(data)
{
$('#tbl-projects').html(data);
$('#tbl-projects').dataTable({
"aaData": data,
"scrollX": true,
"aoColumns": [
{"sTitle": "StudentName", "mData": "name"},
{"sTitle": "Course", "mData": "course"},
{"sTitle": "Fee", "mData": "fee"},
{
"sTitle": "Edit",
"mData": "id",
"render": function (mData, type, row, meta) {
return '<button class="btn btn-xs btn-success" onclick="get_project_details(' + mData + ')">Edit</button>';
}
},
{
"sTitle": "Delete",
"mData": "id",
"render": function (mData, type, row, meta) {
return '<button class="btn btn-xs btn-primary" onclick="Remove_details(' + mData + ')">Delete</button>';
}
}
]
});
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr.responseText);
$.alert({
title: 'Fail!',
// content: xhr.responseJSON.errors.product_code + '<br>' + xhr.responseJSON.msg,
type: 'red',
autoClose: 'ok|2000'
});
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Save');
}
});
}
</Script>
this is the Jsp code
all_project.jsp JSP CODE
<% Class.forName("com.mysql.jdbc.Driver"); %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*" %>
<%
Connection con;
PreparedStatement pst;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/studcrud", "root","");
String query="select * from record";
Statement stmt=con.createStatement();
rs=stmt.executeQuery(query);
while(rs.next())
{
String id =rs.getString("id");
String name =rs.getString("name");
String course =rs.getString("course");
String fee =rs.getString("fee");
out.println(id);
out.println(name);
out.println(course);
out.println(fee);
}
%>
data displayed on the console look like this
**1
john
java
10000
2
Raja
C#
7000
3
sad
asd
2323
4
Nishan
Jsp
12000**
but but display on the datatable
Add the data into the database code JSP Ajax
function addProject()
{
if($("#frmProject").valid())
{
var url= '';
var dat = '';
var method = '';
if(isNew == true)
{
url = 'add.jsp';
data = $('#frmProject').serialize();
method = 'POST';
}
else
{
url = 'update_project.jsp';
data = $('#frmProject').serialize() + "&project_id=" + project_id;
method = 'POST';
}
$.ajax({
type : method,
url : url,
dataType : 'JSON',
success : function (data)
{
$('#frmProject')[0].reset();
$('#save').html('');
$('#save').append('Add');
var msg;
get_all();
if(isNew)
{
msg = "Course Created";
}
else
{
msg = "Course Updated";
}
isNew = true;
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr.responseText);
$.alert({
title: 'Fail!',
// content: xhr.responseJSON.errors.product_code + '<br>' + xhr.responseJSON.msg,
type: 'red',
autoClose: 'ok|2000'
});
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Save');
}
});
}
}
add.jsp
<%#page import="java.sql.*" %>
<% Class.forName("com.mysql.jdbc.Driver"); %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
String studname = request.getParameter("studname");
String course = request.getParameter("course");
String fee = request.getParameter("fee");
Connection con;
PreparedStatement pst;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/studcrud", "root","");
pst = con.prepareStatement("insert into records(name,course,fee)values(?,?,?)");
pst.setString(1,studname);
pst.setString(2,course);
pst.setString(3,fee);
pst.executeUpdate();
%>
With version 1.10.0 of DataTables, it is built-in and easy:
var table = $('#example').DataTable();
table.ajax.reload();
Or may be :
$('#example').DataTable().ajax.reload();

How to send data from one jsp to another jsp and display data using ajax

I'm very new to ajax and jquery. I have a problem when using jsp and ajax to send data.
I know how to display result (Here I use a table) in the same page using ajax.
Now I want to click a button in the first jsp (the click button uses ajax to call servlet controller so as to get data from database, and then converting the data to json format), then show the result in the second jsp, but I was stuck how to do it.
Here's the code:
test.jsp
<body>
<input type='button' value='Show' id='ShowButton' />
</body>
<script type='text/javascript'>
$(document).ready(function() {
$("#ShowButton").click(function(event) {
$.ajax({
type : "POST",
url : "controller.view",
dataType : "json",
success : function(data) {
$.each(data, function (index, element) {
var showContent = '';
showContent += '<tr><td>' + element.cpId + '</td>
<td>' + element.cpName + '</td><td>'
+ element.createDate + '</td><td>' +
element.enable + '</td></tr>';
$("#content tbody").append(showContent);
});
}
});
});
});
</script>
test2.jsp
<body>
<div >
<table id='content'>
<thead>
<tr>
<th>ID</th>
<th>Content Provider Name</th>
<th>Create Date</th>
<th>Enable</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
Thanks.
//inside button click
$.ajax({
url: 'SaveData',
method: 'POST',
data: {
fname: $('#fname').val(),
sname: $('#sname').val(),
age: $('#age').val(),
address: $('#address').val(),
email: $('#email').val(),
gender: $('.gender:checked').val(),
phone: $('#phone').val(),
password: $('#password').val()
},
success: function (data) {
data = JSON.parse(data);
if (data.responce == 1)
alert("Success");
else
alert("Error");
},
error: function (error) {
console.log(error);
}
});

Send and Retrieve Data using JSON and AJAX

I have the following front end code, I need to get the textfield(id=uid) value and parse it to the servlet and based on that value, fill the other two textfields(It's a Search Function), But following code only retrieves the values, couldn't send the "uid". How could I do that? Please help me.
<script type="text/javascript">
$(document).ready(function(){
$('#getData').click(function(){
$.ajax({
url:'JsonServlet',
type:'post',
dataType: 'json',
success: function(data) {
$('#uname').val(data.uname);
$('#uadd').val(data.uadd);
}
});
});
});
</script>
</head>
<body>
UserID:<input name="userid" type="text" id="uid"/><br/>
Name:<input type="text" id="uname"/>
Address:<input type="text" id="uadd"/>
<input type="button" id="getData" value="Get Data"/>
My servlet Code looks like this
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String userid = request.getParameter("userid");
ResultSet rs = db.selectQuery("select * from tbl_user where userid = '"+userid+"'");
JSONObject json = new JSONObject();
while (rs.next()) {
json.put("uname", rs.getString("username"));
json.put("uadd", rs.getString("useraddress"));
}
//json.put("uname", "user1");
// json.put("uadd", "address1");
out.print(json);
} catch (Exception e) {
e.printStackTrace();
}
your ajax should like this..
$.ajax({
url:'JsonServlet?userid='+document.getElementById("uid").value,
type:'post',
dataType: 'json',
success: function(data) {
$('#uname').val(data.uname);
$('#uadd').val(data.uadd);
}
});
});
the you should able to use String userid = request.getParameter("userid");

table search data can be shown... search function ok... display error

<in search.php>
<?php require_once("../includes/session.php"); ?>
<?php require_once("../includes/connection.php") ?>
<?php require_once("../includes/functions.php") ?>
<?php
$searchq = $_POST['searchq'];
$tablehead="<tr><th>Product Name</th><th>Category</th><th>Price</th><th>Discount</th><th>Edit</th></tr>";
$tabledata = "";
if(empty($searchq)) {
echo "";
} else {
//If there is text in the search field, this code is executed every time the input changes.
echo "<div id='results'-->"; //this div is used to contain the results. Mostly used for styling.
//This query searches the name field for whatever the input is.
$sql = "SELECT * FROM `tblstudent` WHERE `student_id` LIKE '%$searchq%' or `name` LIKE '%$searchq%' or `email` LIKE '%$searchq%'";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
$student_id=htmlentities($row['student_id']);
$hashed_password=htmlentities($row['hashed_password']);
$name=htmlentities($row['name']);
$email=htmlentities($row['email']);
"this is the part that i add on but not work, error-free"
$tabledata.="<tr id='$id' class='edit_tr'><td class='edit_td' >
<span id='one_$id' class='text'>$student_id</span>
<input type='text' value='$student_id' class='editbox' id='one_input_$id' />
</td>
<td class='edit_td' >
<span id='two_$id' class='text'>$hashed_password</span>
<input type='text' value='$hashed_password' class='editbox' id='two_input_$id'/>
</td>
<td class='edit_td' >
<span id='three_$id' class='text'>$name $</span>
<input type='text' value='$name' class='editbox' id='three_input_$id'/>
</td>
<td class='edit_td' >
<span id='four_$id' class='text'>$email $</span>
<input type='text' value='$email' class='editbox' id='four_input_$id'/>
</td>
<td><a href='#' class='delete' id='$id'> X </a></td>
</tr>";
}
$finaldata = "<table width='100%'>". $tablehead . $tabledata . "</table>"; // Content for Data
}
echo "</div>";
?>
this is the js query plug in.
<EditDeletePage.js>
$(document).ready(function()
{
$(".delete").live('click',function()
{
var id = $(this).attr('id');
var b=$(this).parent().parent();
var dataString = 'id='+ id;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "delete_ajax.php",
data: dataString,
cache: false,
success: function(e)
{
b.hide();
e.stopImmediatePropagation();
}
});
return false;
}
});
$(".edit_tr").live('click',function()
{
var ID=$(this).attr('id');
$("#one_"+ID).hide();
$("#two_"+ID).hide();
$("#three_"+ID).hide();
$("#four_"+ID).hide();
$("#one_input_"+ID).show();
$("#two_input_"+ID).show();
$("#three_input_"+ID).show();
$("#four_input_"+ID).show();
}).live('change',function(e)
{
var ID=$(this).attr('id');
var one_val=$("#one_input_"+ID).val();
var two_val=$("#two_input_"+ID).val();
var three_val=$("#three_input_"+ID).val();
var four_val=$("#four_input_"+ID).val();
var dataString = 'id='+ ID +'&name='+one_val+'&category='+two_val+'&price='+three_val+'&discount='+four_val;
if(one_val.length>0&& two_val.length>0 && three_val.length>0 && four_val.length>0)
{
$.ajax({
type: "POST",
url: "live_edit_ajax.php",
data: dataString,
cache: false,
success: function(e)
{
$("#one_"+ID).html(one_val);
$("#two_"+ID).html(two_val);
$("#three_"+ID).html(three_val);
$("#four_"+ID).html(four_val);
e.stopImmediatePropagation();
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").live("mouseup",function(e)
{
e.stopImmediatePropagation();
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
//Pagination
function loading_show(){
$('#loading').html("<img src='images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
$.ajax
({
type: "POST",
url: "load_data.php",
data: "page="+page,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val("").focus();
return false;
}
});
});
I edit from the http://palavas.biz/forum/viewtopic.php?f=51&t=4143&sid=9241f1f287fc672cc32f91a06b93f4c3#.UjqVx9Jmim4 but not work... i try to change the function that already have a table display to a search function only display out. but unfortunately I can't display out the data which list inside the table when type words in the search keyword textbox.

Categories