how to use ajax with datatable , django - javascript

i'm trying to fetching data using ajax , and display data into datatable showing data is working fine , but when i try to search or doing some sort into the datatable , it lost the data , and requires to reload the page again ?!
class MainGroup(models.Model):
admin = models.ForeignKey(User,on_delete=models.CASCADE)
main_type = models.CharField(max_length=40,unique=True)
date = models.DateTimeField(auto_now_add=True)
my views.py
def list_maingroup(request):
lists = MainGroup.objects.all().order_by('-pk')
data = []
for obj in lists:
item = {
'id':obj.id,
'admin':obj.admin.username,
'main_type':obj.main_type,
'date':obj.date
}
data.append(item)
return JsonResponse({'data':data})
my templates
const form = document.getElementById('main_form')
form.addEventListener("submit",submitHandler);
function submitHandler(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url 'products:maingroup' %}',
data : $('#main_form').serialize(),
dataType: 'json',
success: successFunction,
});
}
function successFunction(data) {
if (data.success) {
form.reset();
alertify.success("added")
}
else if(data.error_code=='invalid'){
for(var key in data.error_msg){
if(key == 'main_type'){
document.getElementById('main_error').removeAttribute('hidden')
document.getElementById('main_error').innerHTML = data.error_msg[key][0]
}
}
}
}
$.ajax({
type:'GET',
url:'{% url 'products:list-maingroup' %}',
success:function(response){
console.log(response)
data = response.data
var k = '<tbody>'
for(i = 0;i < data.length; i++){
k+= '<tr>';
k+= '<td>' + data[i]['id'] + '</td>';
k+= '<td>' + data[i]["admin"] + '</td>';
k+= '<td>' + data[i]["main_type"] + '</td>';
k+= '<td>' + data[i]["date"] + '</td>';
k+= '</tr>'
}
k+='</tbody>'
document.getElementById('tableData').innerHTML = k
}
})
<div class="col-md-12">
<!-- general form elements -->
<div class="card card-info">
<div class="card-header">
<div class="card-tools">
<button type="button" class="btn btn-tool" data-toggle="collapse" data-target="#main_form" aria-expanded="false" aria-controls="main_form">
<i class="fas fa-minus"></i>
</button>
</div>
<h3 class="text-center">main</h3>
</div>
<form id="main_form" role="form" method="POST">{% csrf_token %}
<div class="card-body">
<div class="form-group row">
<label for="mainGroup" class="col-sm-2 control-label">name</label>
<div class="col-sm-10">
{{form.main_type | attr:'id:mainGroup'}}
<p id="main_error" class="alert alert-danger" aria-disabled="true" hidden></p>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-success">زیادکردن</button>
</div>
</form>
</div>
</div>
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="text-center">infomations</h3>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive">
<table id="maingroupid" class="table table-bordered table-striped text-center">
<thead>
<tr>
<th>#</th>
<th>admin</th>
<th>name</th>
<th>date</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</tfoot>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<script>
$('#maingroupid').dataTable({})
</script>
and also i tried this to serialize my data
def list_maingroup(request):
lists = MainGroup.objects.all().order_by('-pk')
list_serializers = serializers.serialize('json',lists)
return HttpResponse(list_serializers,content_type='application/json')
with this ajax request
$.ajax({
type:'GET',
url:'{% url 'products:list-maingroup' %}',
success:function(data){
console.log(data)
console.log(data)
var k = '<tbody>'
for(i = 0;i < data.length; i++){
const date = new Date(data[i]["fields"]["date"]).toLocaleString();
k+= '<tr>';
k+= '<td>' + data[i]['fields']['id'] + '</td>';
k+= '<td>' + data[i]['fields']["admin"] + '</td>';
k+= '<td>' + data[i]['fields']["main_type"] + '</td>';
k+= '<td>' + date + '</td>';
k+= '</tr>'
}
k+='</tbody>'
document.getElementById('tableData').innerHTML = k
}
})
but still during using datatable search and sorting it lost the existing data , and requires to reload the page to display again!it there something i've done wrong please ?!

for those who faced this problem , i just moved $('#maingroupid').dataTable({}) to ajax call function and it works fine
thank you

Related

Posting Inputs to PHP inside HTML <table>

I'm pretty new to HTML, PHP, and javascript. So I'm developing a simple music search website. So basically after entering a keyword, my web will show up a list of possible results, then clicking on a result will redirect me to a music player and start playing the music.
This is my HTML file:
<div class="container">
<div class="row">
<h1>Search Results</h1>
<!-- BEGIN SEARCH RESULT -->
<div class="col-md-12">
<div class="grid search">
<div class="grid-body">
<div class="row">
<div class="table-responsive">
<table class="table table-hover">
<tbody id="mytable">
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
And I will insert the search results into the table with javascript
<script>
window.onload= function () {
var results = <?php echo json_encode($result_array); ?>;
for (i=1;i<=results.length;i++){
document.getElementById("mytable").innerHTML += '<tr action="get_music.php" method="post"><td class= "number text-center">' + i +'</td> <td><input type="hidden" name="name" value='+results[i-1][0]+'/></td></tr>' ;
}
}
</sript>
My problem is, whenever I click on a result (or a table row specifically), I won't be redirected to get_music.php and I also can't post my inputs into the get_music.php file.
I know my code is a mess, but please help! Thanks!
Update - Added some pictures just to describe it clearer!
Photo Link
So, I've searched a keyword and got more than one results, I wish to pass 3 values ( name, album, artist ) from the result I clicked on to get_music.php
Update - It works! Thanks to Agustin Mita for the help!
So this is my final code
<script>
window.onload= function() {
getDataPHP();
}
function getDataPHP(){
var results = <?php echo json_encode($result_array); ?>;
renderView(results);
}
function renderView(results){
var data = "";
for (i=0;i<results.length;i++){
data += '<tr>';
data += '<td class="number text-center">' + (i+1) + '</td>';
data += '<td class="image" align="left"><img src="https://discussions.apple.com/content/attachment/881765040" alt=""></td>';
data += '<td class="product"><strong>'+results[i][0]+'</strong><br>'+results[i][1]+'<br>'+results[i][2]+'</td>';
data += '<td><form method="post" action="get_music.php">';
data += '<input type="hidden" value="'+results[i][0]+'" name="name" />';
data += '<input type="hidden" value="'+results[i][1]+'" name="album" />';
data += '<input type="hidden" value="'+results[i][2]+'" name="author" />';
data += '<br><input style="float: right;" type="submit" value="Play music" />';
data += '</form></td>';
data += '</tr>';
}
document.getElementById('mytable').innerHTML += data;
}
</script>
You can add form tag before table tag:
<form id="myForm" method="POST" action="get_music.php">
<table class="table table-hover">
<tbody id="mytable">
</tbody>
</table>
</form>
On javascript can submit with onclick:
data += '<td onclick="document.getElementById(\'myForm\').submit()" > Any text</td>';
Example:
Nota: On php pageyou can retrieve data with $_POST function
window.onload= function() {
getData();
}
function getData(){
fetch("https://jsonplaceholder.typicode.com/todos").then(response => response.json()).then((json) => renderView(json));
}
function getDataPHP(){
//var results = <?php echo json_encode($result_array); ?>;
//renderView(results);
}
function renderView(results){
var data = "";
for (i=0;i<results.length;i++){
data += '<tr>';
data += '<td onclick="document.getElementById(\'myForm\').submit()" class= "number text-center">';
data += results[i].id;
data += '</td>';
data += '<td><input type="submit" value="Go '+results[i].id+'" name="'+results[i].id+'" /></td>';
data += '</tr>';
}
document.getElementById('mytable').innerHTML += data;
}
td {
cursor: pointer;
}
<div class="container">
<div class="row">
<h1 id="titleBig">Search Results</h1>
<!-- BEGIN SEARCH RESULT -->
<div class="col-md-12">
<div class="grid search">
<div class="grid-body">
<div class="row">
<div class="table-responsive">
<form id="myForm" method="POST" action="get_music.php">
<table class="table table-hover">
<tbody id="mytable">
</tbody>
</table>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Update
#KuanyuChwn You need a 3 inputs fields with different name attribute and submit button
data += '<tr>';
data += '<td onclick="document.getElementById(\'myForm\').submit()" class= "number text-center">';
data += results[i].id;
data += '</td>';
data += '<td><input type="text" value="'+results[i].id+'" name="valueA" /></td>';
data += '<td><input type="text" value="'+results[i].title+'" name="valueB" /></td>';
data += '<td><input type="text" value="'+results[i].title+'-valueC'+'" name="valueC" /></td>';
data += '<td><input type="submit" value="Send" /></td>';
data += '</tr>';
If you want to post it, it must be inside the form tag. You should also add a submit button. If you want the line to go when you click it, you can use the get method with the a tag. If you want to click on the line and perform post, I suggest you look at ajax.

Cannot fit autocomplete search result inside HTML table with Jquery, Ajax, JSP

So I have this App using AJAX technique with jQuery library to call the Spring-boot REST controller method. The app works but I cant make the searchresult to fit inside HTML tables.
result
HTML code:
<div align="center">
<div class="ui-widget">
<p>Type a product</p>
<label for="automplete-1">Tags: </label>
<input type="text" id="productName">
</div>
</div>
<br>
<!-- <br> Result -->
<br>
<div class="table table-bordered table-striped" id="result_table">
<table style="width: 50%;">
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</table>
</div>
JavaScript code:
$(document).ready(function() {
$('#productName')
.autocomplete({
minLength: 2,
source: '${pageContext.request.contextPath }/product/search',
/* declare sourc variable */
select: function(event, ui) {
/* click event dans ui to fire method*/
/* alert(event) */
var inputFromBox = ui.item.label;
var searchResults = [];
var html_to_append = '';
$.ajax({
type: 'GET',
url: '${pageContext.request.contextPath }/product/search_full?inputParam=' + inputFromBox,
dataType: 'json',
success: function(response) {
console.log(response);
$.each(response, function(i, item) {
html_to_append += '<tr>';
html_to_append += '<td >' + item.id + '</td>';
html_to_append += '<td>' + item.name + '</td>';
html_to_append += '<td>' + item.description + '</td>';
html_to_append += '<td>' + item.price + '</td>';
html_to_append += '</tr>';
});
$("#result_table table").append(html_to_append);
},
});
}
});
});
Since your element with the id result_table is a <div>, NOT a table.
<div class="table table-bordered table-striped" id="result_table">
<table style="width: 50%;">
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</table>
</div>
So, you will need to change:
$("#result_table").append(html_to_append);
to
$("#result_table table").append(html_to_append);

How to reload view after AJAX POST

Being new to AJAX I have encountered this problem and have had no luck resolving it. I want my table to be refreshed after an ajax post to review an object, everything I've tried has been futile.
Assume the ajax response is a JSON result, to avoid posting my OnPost() code.
I send the Id of the product using ajax and then use that Id to remove the product
I then call the same method OnGet() uses to populate the tables which returns the updated list. In chrome debug tools I see the response successfully returns with the updated list. I just don't know how to get it across back to my list. Thanks in advance guys.
#Html.AntiForgeryToken()
<table id="shoppingBag" class="table">
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Price</th>
<th scope="col">Quantity</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.ShoppingBagItems)
{
<tr>
<td>
#item.Product.Name
</td>
<td>
#item.Price.ToString("C")
</td>
<td>
<input value="#item.Quantity" size="1" maxlength="1" class="text-center" />
</td>
<td>
<button onclick="remove(#item.Product.Id.ToString())" class="close">
<span aria-hidden="true">×</span>
</button>
</td>
</tr>
}
</tbody>
</table>
<script>
function remove(id) {
$.ajax({
type: 'POST',
url: 'ShoppingBag?handler=Delete',
headers: {
"XSRF-TOKEN": $('input:hidden[name="__RequestVerificationToken"]').val()
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: ''+id+'',
sucess: function (response) {
append_json(response);
}
});
}
function append_json(data){
var table = document.getElementById('shoppingBag');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' +
object.product.name +
'</td>' +
'<td>' +
object.price +
'</td>' +
'<td>' +
object.quantity +
'</td>';
table.appendChild(tr);
});
}
</script>
In Ajax success method after this append_json(response);add below code to refresh the table
$("#shoppingBag").load(window.location + " #shoppingBag");
change:
var table = document.getElementById('shoppingBag');
to:
var table = $('#shoppingBag tbody');
AND
change:
table.appendChild(tr);
to:
table.append(tr);
you are appending your data to main <table> if you inspect your table you can see the appended html.but you need to append data in body of table
for this you can use $("#shoppingBag tbody").append(tr);
or you can add id to <body> like <tbody id="myTestTableBody"> and use this in to your JavaScript
function append_json(data){
var table = document.getElementById('myTestTableBody');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' +
object.product.name +
'</td>' +
'<td>' +
object.price +
'</td>' +
'<td>' +
object.quantity +
'</td>';
table.appendChild(tr);
});
}
I have added a sample code that how you can append data to existing table
var page=1;
function AddData() {
$.ajax({
url: "https://reqres.in/api/users?page="+page,
type: "GET",
success: function(response){
append_json(response.data);
}
});
page++;
}
function append_json(data){
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' +
object.first_name +
'</td>' +
'<td>' +
object.last_name +
'</td>' +
'<td>' +
'<img src ='+object.avatar +' width="50px" height="50px" />'+
'</td>';
$("#shoppingBag tbody").append(tr);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="Add Data" onclick="AddData()">
<table id="shoppingBag" class="table">
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Price</th>
<th scope="col">Quantity</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

To pass the "rowcount" (Table Row Count) from jquery to "For Loop" (#for (int i = 0; i < rowCount; i++)) inside the .CSHTML

In MVC5, I tried to add/remove rows with glyphicon. I want to pass the "rowcount" (Table Row Count) from jquery to "For Loop" (#for (int i = 0; i < rowCount; i++)) inside the .CSHTML.
Please refer the image which I tried to achieve.
Script:
<script>
$(function () {
$('.glyphicon-plus').click(function () {
var sds = $(this);
$(this).closest("tr").clone(true).appendTo('#ruleTable');
var **rowCount** = $('#ruleTable tr').length;
});
$('.glyphicon-remove').click(function () {
$(this).closest("tr").remove();
});
});
</script>
HTML.BeginForm :
#for (int i = 0; i < rowCount; i++){
<tr>
<td>
<span class="glyphicon glyphicon-plus" stye="color:lawngreen"></span>
<span class="glyphicon glyphicon-remove" style="color:red"></span>
</td>
<td> #Html.TextBox("[" + i + "].DepartmentCode") </td>
<td> #Html.TextBox("[" + i + "].DepartmentName")</td>
</tr>
}
Thanks...
Its Not Possible,Jquery is client side for loop in server side. so you can use One javascript or jquery function and use ajax to make this functionalities.
Thanks,
You can try like this
html
<div class="table-responsive" id="DivTable">
<table class="table table-bordered" id="tbl">
<thead>
<tr>
<td>Name</td>
<td>Age</td>
<td>DOB</td>
<td>Salary</td>
<td>Industry</td>
<td>Action</td>
</tr>
</thead>
<tbody id="dtEmployeeDetails">
</table>
</div>
javascript
function GetEmployeeDetails() {
var EmployeeArray = [];
$("#dtEmployeeDetails").empty();
$.ajax({
type: "POST",
url: '#Url.Action("GetEmployeeDetails", "Employee")',
dataType: 'json',
//data: JSON.stringify({ id: '2' }),
contentType: "application/json; charset=utf-8",
success: function (data) {
$.each(data, function (key, val) {
EmployeeArray[key] = '<tr>' +
'<td>' + val.Name + '</td>' +
'<td>' + val.DateofBirth + '</td>' +
'<td>' + val.Age + '</td>' +
'<td>' + Industry + '</td>' +
'<td>' + val.Salary + '</td>' +
'<td>' + '<a class="btn btn-success btn-xs" title="Edit" id="' + val.EmpID + '" onclick="EditEmployeeDetails(this.id);">' + '<span class="glyphicon glyphicon-pencil"></span></a> ' +
'<a class="btn btn-danger btn-xs" title="Delete" id="' + val.EmpID + '" onclick="DeleteEmployeeDetails(this.id);"><span class="glyphicon glyphicon-trash"></span></a></td></tr>';
});
$("#dtEmployeeDetails").html(EmployeeArray.join(""));
if (data.length == 0) {
$("#dtEmployeeDetails").append('<td colspan="6" class="text-center">No Record Found.</td>');
}
}
});
}

show data when dropdown change occurs in laravel

I have a data in the database with 2 table called registrations, questions i a need to show registrations table data based on questions question_schedul(considered as status)=1 or 2, In my index page there is a drop-down contains 24 hours and 15 days it related to question_schedul(status).when I select a 24 hours I need to show data corresponding to that selected status
Javascript code for dropdown
$(function () {
$("#dropselect").change(function () {
let $value;
if ($(this).val() === "24Hours") {
$value = $(this).val();
$.ajax({
type: 'GET',
url: '{{\Illuminate\Support\Facades\URL::to('tracks24or15')}}',
data: {'dropselect': $value},
success: function (data) {
$('#listdetails').html(data);
// console.log(data);
}
});
}
else {
if ($(this).val() === "15Days") {
$value = $(this).val();
$.ajax({
type: 'GET',
url: '{{\Illuminate\Support\Facades\URL::to('tracks24or15')}}',
data: {'dropselect': $value},
success: function (data) {
$('#listdetails').html(data);
// console.log(data);
});
}
else
{
alert('Select Status');
}
});
});
Index Page
<div class="content-page">
<!-- Start content -->
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="page-title-box">
<h4 class="page-title float-left">SSI TRACK</h4>
<div class="clearfix"></div>
</div>
</div>
</div>
<!-- end row -->
<div class="row">
<div class="col-12">
<div class="card-box table-responsive">
<h4 class="m-t-0 header-title"><b>SSI TRACKS</b></h4>
<div id="datatable_wrapper" class="dataTables_wrapper container-fluid dt-bootstrap4 no-footer">
<div class="row">
<div class="col-sm-6">
<select class="form-control" style="width: 150px" id="dropselect" name="dropselect">
<option>Select Status</option>
<option value="24Hours">24 Hours</option>
<option value="15Days">15 Days</option>
{{--<option value="3">All</option>--}}
</select>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<table id="datatable" class="table table-bordered dataTable table-responsive-lg">
<thead>
<tr>
<th>slno</th>
<th>Address</th>
<th>Model</th>
<th>Chassis</th>
<th>Delivery Date</th>
<th>Call</th>
</tr>
</thead>
<tbody id="listdetails">
#foreach($registeration as $registerations)
<tr>
<td class="sorting_1">{{$loop->iteration}}</td>
<td>{{$registerations->address}}</td>
<td>{{$registerations->model}}</td>
<td>{{$registerations->chassis}}</td>
<td>{{$registerations->delivery_date}}</td>
<td>
<button class="btn btn-primary btn-rounded button">Call Customer
</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
My Controller with function
public function tracks24or15(Request $request)
{
$register = DB::table('registrations')
->join('questions', 'registrations.registration_id', '=', 'questions.question_id')
->select('address', 'model', 'chassis', 'delivery_date')
->where([["questions.question_schedul", "=", 1] || ["questions.question_schedul", "=", 2] ])
->get();
$output = "";
$count = 1;
foreach ($register as $key => $reg) {
$output .= '<tr>' .
'<td>' . $count++ . '</td>' .
'<td>' . $reg->address . '</td>' .
'<td>' . $reg->model . '</td>' .
'<td>' . $reg->chassis . '</td>' .
'<td>' . $reg->delivery_date . '</td>' .
'<td>' . '<button>Callback</button>'. '</td>' .
// '<td>' . '..' . '<img src="assets/images/select.jpg" class="imgsize">.' . '.' . '</td>' .
'</tr>';
}
return Response($output);
}
Try changing your js
Change url
url: {{url("tracks24or15")}}
Adding datatype in ajax call
dataType: 'json',
And as both of your ajax call is same I merged into one
Javascript code for dropdown
$(function () {
$("#dropselect").change(function () {
let $value;
if (($(this).val() === "24Hours") || ($(this).val() === "15Days")) {
$value = $(this).val();
$.ajax({
type: 'GET',
url: {{url("tracks24or15")}},
data: {'dropselect': $value},
dataType: 'json',
success: function (data) {
$('#listdetails').html(data);
// console.log(data);
}
});
}
else
{
alert('Select Status');
}
});
});

Categories