Data is not loaded in to Datatable using Jsp Ajex crud - java

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();

Related

Json data how to pass in to DataTable using Jsp

i am creating simple crud system using jsp. data passing through json format i tested through console it is passing well but data is not display on the datatable.i don't why. i wrote 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>
</thead>
</table>
jQuery
<script>
get_all()
function get_all()
{
$('#tbl-projects').dataTable().fnDestroy();
$('#etbl-projects').DataTable().ajax.reload();
$.ajax({
url : "all_project.jsp",
type : "GET",
dataType : "JSON",
success:function(data)
{
alert(data.course);
$('#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);
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Save');
}
});
}
</script>
all_project.jsp
Jsp Page
<%#page import="org.json.simple.JSONObject"%>
<% 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 records";
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");
JSONObject json = new JSONObject();
json.put("name", name);
json.put("course", course);
json.put("fee", fee);
json.put("id", id);
out.print(json);
out.flush();
}
%>
i have tested through the console result. screen shot below
{"fee":"10000","name":"john","course":"java","id":"1"}{"fee":"7000","name":"Raja","course":"C#","id":"2"}{"fee":"2323","name":"sad","course":"asd","id":"3"}{"fee":"12000","name":"Nishan","course":"Jsp","id":"4"}
i have attached the Datatable image below
enter image description here
Your response in JSON format is invalid (missing comas between object).
Use org.json.simple.JSONArray to create a list of objects, for example:
<%#page import="org.json.simple.JSONArray"%>
...
JSONArray list = new JSONArray();
while(rs.next())
{
String id = rs.getString("id");
String name = rs.getString("name");
String course = rs.getString("course");
String fee = rs.getString("fee");
JSONObject obj = new JSONObject();
obj.put("name", name);
obj.put("course", course);
obj.put("fee", fee);
obj.put("id", id);
list.put(obj);
}
out.print(list.toJSONString());
out.flush();

Autocomplete country text box in jsp form with data in my table tbcntry using jquery

//below is my form page with a text box for country i want to display all countries with letters starting and auto completing with values in my database with data for country using jsp,java,jquery
<html>
<head>
<link href = "https://code.jquery.com/ui/1.10.4/themes/uilightness/jquery- ui.css"rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$('#country').focusin(function() {
$("#country").autocomplete("List.jsp");
});
});
</script>
</head>
<body>
<br><br><center>
<font face="verdana" size="2">
<font size="4">Java(jsp)/jQuery Autocompleter Example</font>
<br><br><br><br>
Select Country :
<input type="text" id="country" name="country"/>
</font>
</body>
</html>
//below is the List.jsp page that have connection to database
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%
try {
String s[] = null;
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver found");
String url = "jdbc:mysql://localhost:protNum/dbName";
String user = "";
String pass = "";
System.out.println("Connected....");
Connection con = (Connection) DriverManager.getConnection(url, user, pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from tbctry");
List li = new ArrayList();
while (rs.next()) {
li.add(rs.getString(1));
}
String[] str = new String[li.size()];
Iterator it = li.iterator();
int i = 0;
while (it.hasNext()) {
String p = (String) it.next();
str[i] = p;
i++;
}
//jQuery related start
String query = (String) request.getParameter("q");
int cnt = 1;
for (int j = 0; j < str.length; j++) {
if (str[j].toUpperCase().startsWith(query.toUpperCase())) {
out.print(str[j] + "\n");
if (cnt >= 5)// 5=How many results have to show while we are typing(auto suggestions)
{
break;
}
cnt++;
}
}
//jQuery related end
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
//Below is a implementation of autocomplete using json and jquery
//Jsp form page for entering country name as a text box while user enters the First letter the autocomplete start functioning
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Autocomplete in java web application using Jquery and JSON</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script>
$(document).ready(function() {
$(function() {
$("#search").autocomplete({
source: function(request, response) {
$.ajax({
url: "CountryListCheck",
type: "GET",
data: {
term: request.term
},
dataType: "json",
success: function(data) {
response(data);
}
});
}
});
});
});
</script>
</head>
<body>
<div class="header">
<h3>Autocomplete in java web application using Jquery and JSON</h3>
</div>
<br />
<br />
<div class="search-container">
<div class="ui-widget">
country:
<input type="text" id="search" name="search" class="search" />
</div>
</div>
</body>
</html>
//below is the code to be placed on controller corresponding to url CountryListCheck
"/CountryListCheck":
String term = request.getParameter("term");
System.out.println("Data from ajax call " + term);
ArrayList<String> list = new Op_contact(dcon).getAllCountriesCheck(term);
System.out.println(list);
Json = new Gson().toJson(list);
response.getWriter().write(Json );
//below is the operation class code or database query section
public ArrayList<String> getAllCountriesCheck(String l) {
ArrayList<String> list = new ArrayList<String>();
PreparedStatement ps = null;
String data;
try {
String ch=l+"%";
ps = (PreparedStatement) dcon.con.prepareStatement("SELECT nicename FROM tbctry WHERE nicename LIKE '"+ch+"'");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
data = rs.getString("nicename");
System.out.println(data);
list.add(data);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return list;
}

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");

Add data to a table row using Ajax

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.

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