I'm making ajax table with Node.js. I can update the rows without refreshing whole page, and delete task also. it's not perfect because of below reason, please see the image.
When I update some row, and I click 'remove' button, it is not working. But after I refresh the whole page, it works well. Maybe this is very verbose question, If you have not enough time - please see js file, there is key of problem... Okay, then the codes are :
html : If I load page, the page will find database and show each one. No problem with this I think.
<table id="tb-docs">
<thead>
<tr>
<th width="50">Active</th>
<th width="300">Subject</th>
<th>Content</th>
<th width="110">Action</th>
</tr>
</thead>
<tbody>
<% posts.forEach( function ( post, index ){ %>
<tr>
<td><input type="checkbox"/></td>
<td><%= post.Subject %></td>
<td><%= post.Content %></td>
<td><button onclick="deleteRow(this,'<%= post._id %>')">Remove</button>
</td>
</tr>
<% }); %>
</tbody>
</table>
js : I strongly suspect 'append()' in updateRow function. maybe there is something wrong,
function updateRow(subject, content){
$.ajax({
url: "/",
type: "POST",
data: { 'subject': subject, 'content': content },
success: function(data){
$('#tb-docs').append('<tr>' +
'<td><input type="checkbox" checked/></td>' +
'<td>'+subject+'</td>' +
'<td>'+content+'</td>' +
// *** Here Appended button is not worked !!!! ***
'<td><button onclick="deleteRow('+this+','+data+')">Remove</button></td>' +
'</tr>');
}
});
}
function deleteRow(obj, id) {
$.ajax({
url: "/dbs/destroy/"+id,
type: "POST",
data: { 'id': id },
success: function(data){
$(obj).closest('tr').fadeOut(300,function(){
$(obj).closest('tr').remove();
});
},
});
}
server (node.js)
// update row handler ===============
app.post('/', function (req, res){
new posts({
Subject: req.body.subject,
Content: req.body.content,
Active: true
}).save(function (err, post) {
if (err) return next(err);
res.send(post._id);
});
});
// delete row handler ===============
app.post('/dbs/destroy/:id',function (req, res){
posts.findById(req.params.id, function (err, post){
if (err) res.send(err) ;
post.remove(function(err, todo, next){
if(err) return next(err);
res.sendStatus(200);
});
});
});
I struggled with it for 2 days. This appending row in table is just trick, right? So I think appended 'button' is not worked, but reloaded page 'button' is worked. Then, How can I do action with appended button?
I think a other way, separate this table html file and ajax get call. but I have a lot of tables, so this is very hard works and not efficient way. Could you tell me what is real problem? Sorry for no fiddle because it is related with database. Anyway Thanks for reading.!
Instead of using '+this+' just type this in the onclick function for the deleteRow button.
function updateRow(subject, content){
$.ajax({
url: "/",
type: "POST",
data: { 'subject': subject, 'content': content },
success: function(data){
$('#tb-docs').append('<tr>' +
'<td><input type="checkbox" checked/></td>' +
'<td>'+subject+'</td>' +
'<td>'+content+'</td>' +
// *** Here Appended button is not worked !!!! ***
'<td><button onclick="deleteRow(this,'+data+')">Remove</button></td>' +
'</tr>');
}
});
}
function deleteRow(obj, id) {
$.ajax({
url: "/dbs/destroy/"+id,
type: "POST",
data: { 'id': id },
success: function(data){
$(obj).closest('tr').fadeOut(300,function(){
$(obj).closest('tr').remove();
});
},
});
}
Related
I am trying to send the data of my table with dynamic values to the controller.
<tbody>
#if (ViewBag.data != null)
{
foreach (var item in ViewBag.data)
{
<tr>
<td class="AutoId">#item.AutoID <input type="hidden" name="AutoID" value="#item.AutoID" /></td>
<td class="hove" name="text"> <b>#item.Text</b><br /><label></label></td>
<td class="Active">#item.Active</td>
<td id="oBy" name="OrderBy">#item.OrderBy</td>
</tr>
}
}
above is the table structure
I am using below ajax call to send one field for example...
<script>
$(document).ready(function () {
alert("Test 1");
$("#btnSave").click(function (e) {
alert("Test 2");
$.ajax({
type: "POST",
url: '#Url.Action("LookupManagementUpdate", "Admin", new { Area = "Admin" })',
data: $(".hove").val(),
dataType: 'json',
async: false,
success: function (response) {
Success = true;
},
error: function (response) {
},
});
});
});
</script>
Below is my controller code
public string LookupManagementUpdate(string text)
{
return "answer"+Request["text"]+text;
}
I tried using both Request and parameter method to fetch the data but it does not display the table data.
This is a c# mvc ado.net based project
try using Ajax.BeginForm and ajaxOptions Onsuccess
I just recently learned Django/ajax/datatables. I can project my data using a {%for%} loop and im trying to do the same thing with ajax calls.
My view:
def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
def getfromServer(request):
if is_ajax(request=request) and request.method == "GET":
books= Book.objects.all()
bookserial = serializers.serialize('json', books)
return JsonResponse(bookserial, safe=False)
return JsonResponse({'message':'Wrong validation'})
index.html
<div class="container">
<table id="books" class="display" style="width:100%">
<thead>
<tr>
<th>Book</th>
<th>Author</th>
<th>Genre</th>
<th>Date Publishedd</th>
<th>Copies</th>
</tr>
</thead>
</table>
</div>
<script>
$(document).ready(function() {
$('#books').DataTable({
ajax: {
type: "GET",
datatype : 'json',
url: 'views/getfromServer',
},
columns: [
{ data: 'name' },
{ data: 'author' },
{ data: 'genre' },
{ data: 'pub_date' },
{ data: 'copies' },
]
});
</script>
Im pretty sure it kinda works this way but i just cant figure it out .
jQuery DataTable is a powerful and smart HTML table enhancing plugin provided by jQuery JavaScript library
So it doesn't make sense to put an ajax request inside the .DataTable() method
You have to make the ajax request first:
$.ajax({
type: "GET",
datatype : 'json',
url: 'views/getfromServer',
success: function (result) { // result is the response you get from the server if successful
// Use the data in result to write the values to your html table respectively here
}
error: function (err) {
// handle error
}
})
thats what I came up with but still doesnt seem to do the trick all i get is an empty table .
$.ajax({
type: "GET",
datatype : 'json',
url: "views/getfromServer", // "{% url 'index' %}"
success: function (response) {
var instant = JSON.parse(response[books]);
for book in books {
var fields= instant[book]["fields"];
$("#books tbody").prepend(
`<tr>
<td>${fields["name"]||""}</td>
<td>${fields["author"]||""}</td>
<td>${fields["genre"]||""}</td>
<td>${fields["pub_date"]||""}</td>
<td>${fields["copies"]||""}</td>
</tr>`
)
}
},
error: function (response) {
alert(response["responseJSON"]["error"]);
}
})
$(document).ready(function() {
$('#books').DataTable();
What I usually do is grab the data from the repository and pass that data along to the view via addAttribute, like this:
#GetMapping("html_page")
public String dynamicPage(Model model){
List<MySqlDataDTO> mySqlDataDTO = mySqlRepository.findAllByName(name);
model.addAttribute("mySqlDataDTO", mySqlDataDTO);
return "html_page";
}
Then use thymeleaf to loop through the data and display it in a table, like this:
<table id="table" >
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Fav</th>
</tr>
</thead>
<tbody >
<tr th:each="mySqlDataDTO : ${mySqlDataDTO}" >
<th th:text="${mySqlDataDTO.id}"></th>
<td th:text="${mySqlDataDTO.name}"></td>
<td th:text="${mySqlDataDTO.fav}"></td>
</tr>
</tbody>
</table>
This is all fine but, the issues comes up when the user intially sends the data to the DB, the page would refresh and force the user to the top of the page thus creating a negative user experience.
I figured out how to use ajax to fix the issue of the refreshing page by having the post request go through ajax first like so:
$(document).ready(function () {
$('#form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "POST",
data: $(this).serialize(),
success: function (data) {
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
Which works just fine by sending the data to the DB and not having the page refresh, but the issue is the retrieval of the data after its been sent to the database. I dont quite understand how to then retrieve the data and have it be displayed in a table to the user, here's what I have so far, but doesnt seem to work:
$(document).ready(function () {
$('#form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
$('#table').empty();
$.each(data.items, function(item) {
alert(data.name);
});
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
I added an alert just to see the data as a test. Basically I want to grab the data from the DB like I normally do via my repository, then pass that data to the view to be displayed like this:
But again it should use ajax get, so as soon the user hits submit that table refreshes (not the whole page) and the table reflects the DB data.
First of all, I have to say that I'm beginner with using Ajax... So help me guys.
I want to insert the data into db without refreshing the page. So far, I have following code...
In blade I have a form with an id:
{!! Form::open(['url' => 'addFavorites', 'id' => 'ajax']) !!}
<img align="right" src="{{ asset('/img/icon_add_fav.png')}}">
<input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">
<input type="hidden" name = "idArticle" id="idArticle" value="{{$docinfo['attrs']['sid']}}">
<input type="submit" id="test" value="Ok">
{!! Form::close() !!}
And in controller I have:
public function addFavorites()
{
$idUser = Input::get('idUser');
$idArticle = Input::get('idArticle');
$favorite = new Favorite;
$favorite->idUser = $idUser;
$favorite->idArticle = $idArticle;
$favorite->save();
if ($favorite) {
return response()->json([
'status' => 'success',
'idUser' => $idUser,
'idArticle' => $idArticle]);
} else {
return response()->json([
'status' => 'error']);
}
}
I'm trying with ajax to insert into database:
$('#ajax').submit(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"{{ url('addFavorites') }}",
dataType="json",
data:$('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
}
error: function(data){
alert("Error")
}
});
});
Also in my web.php I have a route for adding favorites. But when I submit the form, it returns me JSON response like this: {"status":"success","idUser":"15","idArticle":"343970"}... It actually inserts into the db, but I want the page not to reload. Just to display alert box.
As #sujivasagam says it's performing a regular post action. Try to replace your javascript with this. I also recognized some syntax error but it is corrected here.
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
You could just replace <input type="submit"> with <button>instead and you'll probably won't be needing event.preventDefault() which prevents the form from posting.
EDIT
Here's an example of getting and posting just with javascript as asked for in comments.
(function() {
// Loads items into html
var pushItemsToList = function(items) {
var items = [];
$.each(items.data, function(i, item) {
items.push('<li>'+item.title+'</li>');
});
$('#the-ul-id').append(items.join(''));
}
// Fetching items
var fetchItems = function() {
$.ajax({
type: "GET",
url: "/items",
success: function(items) {
pushItemsToList(items);
},
error: function(error) {
alert("Error fetching items: " + error);
}
});
}
// Click event, adding item to favorites
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
// Load items (or whatever) when DOM's loaded
$(document).ready(function() {
fetchItems();
});
})();
You are using button type "Submit" which usually submit the form. So make that as button and on click of that call the ajax function
Change your button type to type="button" and add onclick action onclick="yourfunction()". and just put ajax inside your funciton.
Replace input type with button and make onClick listener. Make sure you use this input id in onclick listener:
So:
$('#test').on('click', function(event){
event.preventDefault()
... further code
I would also change the id to something clearer.
I have a table containing this kind of information
I am using knockout js and putting all data on a array and putting it on this table like this.
self.allchildrendata = ko.observableArray();
self.viewAllUserChildrenCard = function () {
$.ajax({
type: 'POST',
url: BASEURL + '/index.php/main/childrenCardInfo',
contentType: 'application/json; charset=utf-8',
dataType :'json'
})
.done(function(childrencards) {
self.allchildrendata.removeAll();
$.each(childrencards, function (index, childrencard) {
self.allchildrendata.push(childrencard);
console.log(self.allchildrendata());
});
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
};
self.viewAllUserChildrenCard();
So next I want to click the add money button for rebecca and want to send the orig id of only rebecca so I can use it to find her in the database and add money, But i am not sure on how to send the orig_id, I tried this way.
self.giveCashtoChild = function(){
$.ajax({
type: 'POST',
url: BASEURL + '/index.php/main/addUserChildrenCash' + "/" + self.allchildrendata().orig_id ,
contentType: 'application/json; charset=utf-8'
})
.done(function() {
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
}
Here is the html code where I have a databind on each of the buttons so I can send the orig id .
<tbody data-bind="foreach: allchildrendata">
<tr>
<td class="text-center"><span data-bind="text : $data.children_name"></span></td>
<td class="text-center"><span data-bind="text : $data.daugther_son"></span></td>
<td class="text-center"><span data-bind="text : $data.amount"></span> $</td>
<td class="text-center"><span class=" glyphicon glyphicon-send"></span></td>
<td class="text-center"><span class=" glyphicon glyphicon-trash"></span></td>
</tr>
</tbody>
So basically I need help to identify which family memeber I am clicking and sending that family memebers orig_id
Whenever you use a click binding, knockout passes the current binding's data and event.
So in your HTML:
<a href="#" data-bind="click : $root.giveCashtoChild">
It calls giveCashToChild with two arguments. Your giveCashToChild method should thus accept two arguments, of which the first will be the child to give cash to.
self.giveCashtoChild = function(data, event) {
var currentChildId = data.orig_id;
// the other stuff..
};