How to fix added parameter in rest call with ajax? - ajax

I'm trying to test Datatables composer with ajax Rest calls to spring RestController. I setup front in wampserver and the back with spring boot.
I'm using the spring tuto to setup the RestController https://spring.io/guides/gs/rest-service/
It works fine, I got Json file while calling the controller. I want to using that resutl and show in Datatables.
The code script.js of the font is :
$(document).ready( function () {
$('#table_id').DataTable( {
"processing": true,
"serverSide": false,
"ajax": {
"url": "http://localhost:8080/greeting",
"type": 'GET',
"dataType": "json",
"data": function (data) {
// console.log(data);
return data = JSON.stringify(data);
}
},
"columns": [
{"data": 'id'},
{"data": 'content'}
]
});
});
html page
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf8" src="script.js"></script>
<meta charset="UTF-8">
<title>Gtreetings</title>
</head>
<h3>Hi, little one </h3>
<body>
<table id="table_id" class="display" style="width:100%">
<thead>
<tr>
<th>id</th>
<th>content</th>
</tr>
</thead>
<tfoot>
<tr>
<th>id</th>
<th>content</th>
</tr>
</tfoot>
</table>
</body>
</html>
I got a weird added parameter {}&=1558786054608
and Cross-Origin Request error on http://localhost:8080/greeting?{}&=1558786054608.
I'm not sure if it is a timestamp, I don't know how to explane this.

First, in your JS script, you have an error in the ajax call, the data means the parameter send not from ajax. here is a correct version of the code.
$(document).ready( function () {
$('#table_id').DataTable({
processing: true,
serverSide: false,
dataType: "json",
ajax: {
url: "http://localhost:8080/greeting",
method: 'GET',
dataSrc: function (json) {
console.log("json",json)
return json;
},
},
columns: [
{data: 'id'},
{data: 'content'}
]
});
});
Second, in the backend on the controller you have to add annotation #CrossOrigin(origins = "*") thus you avoid the error cross-origin.
Finally, Datatable has to have an array in the retune result, and it is not the case in your controller. It returns an object.
I suggest to wrap your object within a list as follows :
#CrossOrigin(origins = "*")
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public List<Greeting> greeting(#RequestParam(value="name", defaultValue="World") String name) {
List<Greeting> ls = new ArrayList<Greeting>();
ls.add(new Greeting(counter.incrementAndGet(),
String.format(template, name)));
return ls;
}
}
I hope it helps.

Related

While implementing Data table in Spring Boot MVC Project with Thymeleaf ,no any data populate in data table

My Service,Controller and Views are :
public class LoadDataService {
public List<Employee> getEmployeeList(){
List<Employee> employeeList = new ArrayList<Employee>();
Employee employee1 = new Employee("Sridharan","Junior Blogger","5000","India");
Employee employee2 = new Employee("Arul Raj","Senior Blogger","105000","China");
Employee employee3 = new Employee("Priya","Associate","21000","Australia");
Employee employee4 = new Employee("Sam","Associate","20030","Australia");
Employee employee5 = new Employee("Ram","Associate","2020","Australia")
employeeList.add(employee5);
employeeList.add(employee4);
employeeList.add(employee3);
employeeList.add(employee2);
employeeList.add(employee1);
return employeeList;
}
#Override
public String toString() {
return "LoadDataService [getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()="
+ super.toString() + "]";
}
}
Controller class :
#Controller
public class JQueryDatatableController {
private static final Logger logger = LoggerFactory.getLogger(JQueryDatatableController.class);
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(Locale locale, Model model) throws JsonGenerationException, JsonMappingException, IOException {
logger.info("Welcome home! The client locale is {}.", locale);
LoadDataService dataService = new LoadDataService();
ObjectMapper mapper = new ObjectMapper();
ModelAndView mav=new ModelAndView();
mav.addObject("employeeList", mapper.writeValueAsString(dataService.getEmployeeList()));
mav.setViewName("index");
return mav;
}
}
data table integration in HTML thymeleaf page is :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Datables Demo</title>
<script type="text/javascript" th:src="#{js/jquery-1.12.1.min.js}" ></script>
<script th:src="#{js/jquery.dataTables.js}"></script>
<!--CSS StyleSheet -->
<link rel="stylesheet" type="text/css" th:href="#{/css/common.css}"/>
<link rel="stylesheet" type="text/css" th:href="#{/css/jquery.dataTables.css}">
</head>
<body>
<div>
<img class="dataTableExample" th:src="#{/images/JQueryDatatableandSpringMVC.png}">
</div>
<table id="example" class="display" cellspacing="0" width="100%" style="overflow-x:auto">
<thead>
<tr>
<th>Name</th>
<th>Designation</th>
<th>Salary</th>
<th>Country</th>
</tr>
</thead>
</table>
<script th:inline="javascript">
$(document).ready(function () {
$('#example').DataTable({
"searching": true,
"serverSide":false,
"paging":true,
"sAjaxSource":"${employeeList}",
"columns": [
{"data": "name"},
{"data": "designation"},
{"data": "salary"},
{"data": "country"}
]
})
});
</script>
</body>
</html>
Screenshot of Error
Try assigning Employee List to 'data' like below,
<script th:inline="javascript">
var empList = ${employeeList};
$(document).ready(function () {
$('#example').DataTable({
"searching": true,
"serverSide":false,
"paging":true,
"data": empList,
"columns": [
{"data": "name"},
{"data": "designation"},
{"data": "salary"},
{"data": "country"}
]
})
});
</script>
https://datatables.net/manual/data/
After multiple try and reading a lot of problem ,i find the answer
<script type="text/javascript" th:inline="javascript">
var empList = [# th:utext="${employeeList}"/];
$(document).ready(function () {
console.log(empList);
$('#example').DataTable({
"aaData":empList,
"aoColumns": [
{"mDataProp": "name"},
{"mDataProp": "designation"},
{"mDataProp": "salary"},
{"mDataProp": "country"}
]
})
});
</script>

angular js ng-repeat is not working

In ng-repeat do not show any data but the data is available in response.
The loop is not working properly.
<html>
<head></head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="thecontroller">
<form>
<tr ng-repeat="x in names">
<td>{{x.name}}</td>
<td>{{x.email}}</td>
<td>{{x.passward}}</td>
</tr>
</form>
</div>
</body>
console.log(response) show the data in console
<script>
var app = angular.module('myApp', []);
app.controller('thecontroller', function($scope, $http) {
$http.get("show.php")
.then(function (response) {
$scope.names=response.data;
console.log(response)
} );
});
</script>
</html>
So I tried your code and have a few corrections, the reason you are not able to see any data may be due to, usage of tr and td tags without the table tag as the parent, please check my below code, where I have added the table and tbody tags, Also, inorder to simulate a http request, I have use the $timeout which will set the data after 3 seconds, please study the example and implement it to your code!
var app = angular.module('myApp', []);
app.controller('thecontroller', function($scope, $http, $timeout) {
var data = [{
name: "one",
email: "one#one.com",
password: "1234"
}, {
name: "two",
email: "two#two.com",
password: "1234"
}, {
name: "three",
email: "three#three.com",
password: "1234"
}, ]
$timeout(function() {
$scope.names = data;
}, 3000);
/*$http.get("show.php")
.then(function(response) {
$scope.names = response.data;
console.log(response)
});*/
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="thecontroller">
<form>
<table>
<tbody>
<tr ng-repeat="x in names">
<td>{{x.name}}</td>
<td>{{x.email}}</td>
<td>{{x.password}}</td>
</tr>
</tbody>
</table>
</form>
</div>
</body>
</html>

Select2 The Result Cannot Be Load in CodeIgniter

When I type in my select box the result always show "The result cannot be load". I am using CodeIgniter for my framework and select2 in my select box and am a newbie in CodeIgniter and Select2. I have already search it through all articles that can be related to my problem but it still can't work. I think I messed my ajax but I don't know how and where I should fix it.
Here is my controller
<?php
class Admin extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('admin_model');
}
function search_book(){
$booksClue = $this->input->get('booksClue');
$data_book = $this->admin_model->get_book($booksClue, 'id_book');
echo json_encode($data_book);
}
}
?>
Here is my model
<?php
class Admin_model extends CI_Model{
function get_book($booksClue, $column){
$this->db->select($column);
$this->db->like('id_book', $booksClue);
$data = $this->db->from('book')->get();
return $data->result_array();
}
}
?>
And here is my view
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$('.searchingBook').select2({
placeholder: 'Masukkan ID Buku',
minimumInputLength: 1,
allowClear: true,
ajax:{
url: "<?php echo base_url(); ?>/admin/searchbook",
dataType: "json",
delay: 250,
data: function(params){
return{
booksClue: params.term
};
},
processResults: function(data){
var results = [];
$.each(data, function(index, item){
results.push({
id: item.id_book,
text: item.id_book
});
});
return{
results: results
};
}
}
});
});
</script>
<table>
<tr>
<td><b>ID Buku</b></td>
<td> : </td>
<td>
<select class="searchingBook" style="width: 500px">
<option></option>
</select>
</td>
</tr>
</table>
<br><br>
</body>
</html>
Big thanks for your help!
Update your model function like below:
function get_book($booksClue, $column){
$this->db->select($column);
$this->db->from('book');
$this->db->like('id_book', $booksClue);
return $this->db->get()->result_array();
}

ASP.net MVC Ajax DataTable Error 7

Kinda newbie when it comes to ASP.net MVC side of things not sure why I am getting Ajax Error 7 in DataTable
here is my code : for cshtml
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Register new Users</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap
/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/
jquery.dataTables.min.css" />
<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
<style>
span.field-validation-error {
color: red;
}
</style>
</head>
<body>
<div style="width:90%; margin:0 auto ">
you are in the Table area
<table id="myDatatable">
<thead>
<tr>
<th>User ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>User Email</th>
<th>Username</th>
<th>Users ImagePath</th>
<th>SSID</th>
</tr>
</thead>
</table>
</div>
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script>
$(document).ready(function () {
var oTable = $('#myDatatable').DataTable({
"ajax": {
"url": '/home/GetUsers',
"type" : "get",
"dataType": "json"
},
"columns": [
{ "data": "Users_ID", "autoWidth": "true" },
{ "data": "Users_Fname", "autoWidth": "true" },
{ "data": "Users_Sname", "autoWidth": "true" },
{ "data": "Users_Email", "autoWidth": "true" },
{ "data": "Users_Usersname", "autoWidth": "true" },
{ "data": "Users_ImagePath", "autoWidth": "true" },
{ "data": "FK_Product_ID", "autoWidth": "true" }
]
})
})
</script>
</body>
</html>
I have tried few stackflow troubleshooting but am not getting anywhere
my file structure name are as follows
under the model folder I have EPOSv3DataModel.edmx
under the home folder I have HomeController.cs file within this
I have the following code :
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to Registration System";
//EPOSv3Entities1 r = new EPOSv3Entities1();
//var data = r.tbl_Users.ToList();
//ViewBag.userdetails = data;
return View();
}
#region Get Users from the database
public ActionResult GetUsers()
{
using (EPOSv3Entities1 entity = new EPOSv3Entities1())
{
// get the data order by firstname
var users = entity.tbl_Users.OrderBy
(a => a.Users_Fname).ToList();
return Json(new { data = users }, JsonRequestBehavior.AllowGet);
}// end of your using statement
}
#endregion
}end of class
}//end of namespace
I was following this video tutorial from: YouTube
and the site where this developer has his code is :ASP.net CRUD DataTable
Very much appreciate your support the table display but does not load any data
also when in URL when I enter the https://localhost/portnumber/Home/GetUsers the ajax error disappears but no loading data.
HELP :(
you can try this
using (EPOSv3Entities1 entity = new EPOSv3Entities1())
{
entity.Configuration.ProxyCreationEnabled = false;
// get the data order by firstname
var users = entity.tbl_Users.OrderBy
(a => a.Users_Fname).ToList();
return Json(new { data = users }, JsonRequestBehavior.AllowGet);
}// end of your using statement
you are using entity framework generated proxy object which might be causing problems in serializing

Anti Forge Token and Ajax JSON Post Does not Work

I am running MVC3, .Net 4 and VS2010. I have following sample project to illustrate the problem.
My controller code
namespace AntiForgeAjaxTest.Controllers
{
public class IndexController : Controller
{
public ActionResult Index()
{
MyData d = new MyData();
d.Age = 20;
d.Name = "Dummy";
return View(d);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(MyData data)
{
NameValueCollection nc = Request.Form;
return View(data);
}
protected override void ExecuteCore()
{
base.ExecuteCore();
}
}
}
My view and JavaScript code
#model AntiForgeAjaxTest.Models.MyData
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
#using (Html.BeginForm("Index", "Index"))
{
#Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>#Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
alert(JSON.stringify(myObject));
$.ajax({
type: 'POST',
url: '/Index/Index',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(myObject),
success: function (result) {
alert(result);
},
error: function (request, error) {
alert(error);
}
});
});
});
</script>
</body>
</html>
Here I have 2 buttons, the first one triggers form post, the second one triggers Ajax post. The form post works fine, but the Ajax one does not, the server complains A required anti-forgery token was not supplied or was invalid. even though I have included the token in my JSON already.
Any idea what is wrong with my code?
This code works.
#model AntiForgeAjaxTest.Models.MyData
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
#using (Html.BeginForm("Index", "Index"))
{
#Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>#Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
post();
});
});
function post() {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
$.post('/Index/Index/', myObject);
}
</script>
</body>
</html>

Resources