I have a table with some to-do tasks and I want to be able to remove tasks through ajax but I do not know how to refresh my table after deleting.
I already am able to delete a task but I do not see the task removed until i refresh the page. I am sending some foo message to the template and I can see it but what I dont know is how to send the result of my query again and send a bunch of tasks to the template and show them in the table
this is my code
controller
class Delete(webapp2.RequestHandler):
def get(self):
string_id = self.request.get("task")[12:28]
task_key = ndb.Key('Task', int(string_id))
task_key.delete()
session = Session(self.request)
user = User.get_by_id(session.email)
userkey=user.key
tasks=Task.query(Task.author==userkey)
response_data = {'message' : 'foo'}
self.response.out.headers['Content-Type'] = 'text/json'
self.response.out.write(json.dumps(response_data))
return
class MainPage(webapp2.RequestHandler):
#login_required
def get(self):
session = Session(self.request)
user = User.get_by_id(session.email)
userkey=user.key
tasks=Task.query(Task.author==userkey)
template_values = {
'tasks': tasks
}
template = 'index.html'
render_template(self,template,template_values)
javascript
$(document).ready(function(){
$('.delete-button').click(function() {
$.ajax({
type: 'GET',
url: '/delete',
data: $('#delete-form').serialize(),
success: showData,
error: null
});
return false;
});
})
function showData(data){
$('#prueba').html(data.message)
}
template
<table >
<thead>
<tr>
<th>Nombre</th>
<th>Descripcion</th>
<th>Fecha</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
{% for task in tasks %}
<tr>
<td>{{ task.name }}</td>
<td>{{ task.description }}</td>
<td>{{ task.date|datetime }}</td>
<td>{{ task.status }}</td>
<td>
<form action="#" id="delete-form">
<input type="hidden" name="task" value="{{task.key}}">
<input type="submit" value="Eliminar" class="delete-button">
</form>
</td>
</tr>
{% endfor %}
<tbody>
</table>
<div id="prueba"></div>
Just refresh the page or after deleting in ajax make a Jquery function which will dynamically remove this object from your view. This are only two options you have ;)
For example:
$.ajax({
type: 'GET',
url: '/delete',
data: $('#delete-form').serialize(),
success: showData,
error: null
}, function() {
Your removing function
});
In your removing function you have to just simply find this object which you want to remove and remove it, for example:
$(#ObjectName).parents("li:first").remove();
Related
I'm building a component on my project, which is actually getting all the data and console logging it, but here's the problem: Inside my array of clients, i have some objects (address, documents, ...), and i can't manage to call them on my table.
My script:
<script>
export default {
data: () => ({
clients: [],
}),
methods: {
getClients() {
this.$api
.get("/api_v1/clientes", {
})
.then((response) => {
this.clients = response.data[0];
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
},
mounted() {
this.getClients();
},
};
</script>
My table (inside ):
<tbody>
<tr v-for="client in clients" v-bind:key="client.id">
<td>{{ client.id }}</td>
<td>{{ client.name }}</td>
<td>{{ client.email }}</td>
<td>{{ client.documents.cpf || client.documents.cnpj }}</td>
<td>{{ client.documents.celular }}</td>
<td>{{ client.status }}</td>
<td v-if="client.address">
{{ `${client.address.localidade} / ${client.address.uf}` }}
</td>
<td v-else>-</td>
<td>
<a :href="`/see-client/${client.id}`"
><i class="icon-magnifier"></i
></a>
<i class="icon-check" style="color: green"></i>
<i class="icon-close" style="color: red"></i>
</td>
</tr>
</tbody>
My controller:
public function index(Request $request)
{
$data = [
'pag' => 'All clients',
'link' => '/'
];
return view('clients.index', $data);
}
The data:
Someone have a clue of a different approach i could have? I'm using Vue2. It's one of my first big projects, so previously sorry for any rookie mistake. Thanks for your time and help!
This line is only getting the first client:
this.clients = response.data[0];
response.data is your array of clients (from the looks of things). When you use .data[0], you're getting the first element of the array (i.e. the first client).
Then, this line is trying to loop over 1 client, not an array of clients.
<tr v-for="client in clients" v-bind:key="client.id">
Try changing
this.clients = response.data[0];
to
this.clients = response.data;
If that doesn't work (it looks like you've got a weird data structure), try this instead:
this.clients = response.data.data;
Or this (it's unclear to me how many nested data properties you have):
this.clients = response.data.data.data;
I just made a quick analysis about your code. I think you should polish it a little bit.
Let me start with a quick catch up:
Update yuor js section with:
<script>
export default {
// Please do use the function format instead of lambda expression, it's recommended in the vue2 docs.
data() {
return {
clients: [],
};
},
methods: {
// Change this to an async method, so you can have more control on your code.
async getClients() {
try {
/**
* Here, you should have to know, that your file `routes/api.php` hass all of the prefixed /api routes
* So you have a direct access to /api prefixed routes
* Additionally read a little bit about destructuring.
*/
const response = await this.$api.get("/api/clientes");
// Now, please notice that you have 2 data path names.
this.clients = response.data.data; // {or please follow the correct path to the array container of the clients}.
} catch (e) {
console.log("Check this error: ", e);
}
},
},
// Now, change your mounted to an async method
async mounted() {
// Trust me this is going to work perfectly.
await this.getClients();
},
};
</script>
Now, please, please change your api controller logic to a response()->json(...)
public function index(Request $request)
{
// Your retrieve logic...
return response()->json($data);
}
Finally if you have successfully configured everything abouve, your vue component should be able to retrieve the information correctly, and your tbody must work this way...
<tbody>
<tr v-for="client in clients" v-bind:key="client.id">
<td>{{ client.id }}</td>
<td>{{ client.name }}</td>
<td>{{ client.email }}</td>
<td>{{ client.documents.cpf || client.documents.cnpj }}</td>
<td>{{ client.documents.celular }}</td>
<td>{{ client.status }}</td>
<td v-if="client.address">
<!-- You can replace what you have with: -->
{{ client.address.localidade }} / {{ client.address.uf }}
</td>
<td v-else>
-
</td>
<td>
<a :href="`/see-client/${client.id}`">
<i class="icon-magnifier"></i>
</a>
<i class="icon-check" style="color: green"></i>
<i class="icon-close" style="color: red"></i>
</td>
</tr>
</tbody>
On my HTML template, I am printing a list of my QuerySet that I passed from views.py in Django. I want users to delete an entry from the list without refreshing the page. How do I do that?
urls.py - path("del_trans/<int:trans_num>", views.delete_transaction, name="delete_transaction")
views.py
def delete_transaction(request, trans_id):
user = User.objects.get(username=request.user)
transaction = Transaction.objects.get(ruser=user, id=trans_id)
transaction.delete()
return HttpResponse(status=204)
trans.html
<tr id="trans-{{t.id}}">
<td>{{ t.name }}</td>
<td><button class="btn" onclick="delete_trans({{t.id}})"><span style="cursor:pointer;
color:blue;
text-decoration:underline;">Delete</span></button></td>
</tr>
index.js
function delete_trans(id) {
fetch(`/del_trans/${id}`, {
method: 'PUT',
body: JSON.stringify({
trans_id: id
})
});
document.querySelector('#trans-' + id).style.display = 'none';
}
I am submitting forms via django forms and I want data to refresh on submit in a certain part of the page (div)
$(function () {
$('#post-form').ajaxForm({
success: function (json) {
console.log(json); // log the returned json to the console
$('#this').append('snippet.html')
console.log("success"); // another sanity check
}
}) });
of an html snippet
<div id="this">
<tr>
<th>ID</th>
<th>Дата</th>
<th>Цена</th>
<th>Откуда</th>
<th>Куда</th>
<th>Водитель</th>
</tr>
{% for item in query_set %}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.date }}</td>
<td>{{ item.price }}</td>
<td>{{ item.des_from }}</td>
<td>{{ item.des_to }}</td>
<td>{{ item.driver }}</td>
</tr>
{% endfor %}
</div>
And here is "views" file
def post(self, request):
csrf_token_value = get_token(self.request)
data = {}
form = SchedForm(request.POST)
if form.is_valid():
obj = form.save()
data['result'] = 'Created!'
data['object'] = {
'price': obj.price,
'driver': obj.driver_id,
'des_from': obj.des_from_id,
'des_to': obj.des_to_id,
'date': obj.date,
}
return JsonResponse(data)
else:
return JsonResponse(form.errors)
The problem is I have a JsonResponse in view's return while on the INTERNET I've read that there are two solutions via render_to_response and render_to_string. But as far as I'm concerned to refresh data in forms you need render_to_string. I just don't see a way to include it in the return with JsonResponse
Here table contains book details which contains book name, author, pric, ISBN and category. When user click on Book Name it should pass the data to another page using querystring
<script type="text/javascript" src="book.js">
<body ng-app="mymodule" >
<div ng-controller="myController" >
<table border=2>
<thead>
<tr>
<th>ISBN</th>
<th>NAME</th>
<th>AUTHOR</th>
<th>CATEGORY</th>
<th>PRICE</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="book in books">
<td>{{ book.ISBN }}</td>
<td >{{ book.Name }}</td>
<td>{{ book.Author }}</td>
<td>{{ book.Category }}</td>
<td>{{ book.price }}</td>
</tr>
</tbody>
</table>
books.js
var myapp = angular.module('mymodule', []);
myapp.controller("myController", function($scope, $http,$window) {
$http.get("https://api.myjson.com/bins/p4ujn").then(function(response) {
$scope.books = response.data;
$scope.getdetail=function(){
$scope.getbookdetail=this.book;
$window.location.href = "orderpage.html";
}
});
});
orderpage.html
<script type="text/javascript" src="book.js"></script>
<body ng-app="mymodule" >
<div ng-controller="myController" >
{{getbookdetail.Name}}<br>
{{getbookdetail.Author}}
{{getbookdetail.price }}<br>
</div>
</body
So you said this: 'When user click on Book Name it should pass the data to another page using querystring'
Querystring is not the best method to use for something like this. You're better off learning about ui-router and setting up routes that handle this. You have your initial state, then you can create another state to display each book. Something like this:
.state('initial', {
url: 'some/initial',
template: 'some/initial/template.html',
params: {
name: null,
price: null,
author: null,
isbn: null,
category: null
}
})
.state('read-book-details', {
parent: 'initial',
url: 'some/url',
template: 'some/template.html',
params: {
name: null,
price: null,
author: null,
isbn: null,
category: null
}
})
Then when you're transitioning from one 'state' to another, you do it like so passing along the parameters you want:
$state.go('read-book-details',
{ name: book.name, price: book.price, author: book.author });
On the 'other' page's controller (ie the controller for the 'read-book-details' state) you can inject $state and get the parameters that are passed in via $state.params (ie., $state.params.price)
A second option for you is to have a service that you can store the data in, then retrieve from anywhere else. This obviously becomes useful when you start to pass around larger amounts of data rather than simpler smaller pieces (like name, price).
I'm trying to build a simple search feature, but I can't figure out why my code is not working.
This is the action that I have built to search:
search: function(req, res) {
var criteria = req.param('criteria');
var value = req.param('value');
Human.find().where({ criteria: value }).done(function(err, humans) {
if(err) {
return console.log('Error:' + err);
}else{
res.view({
title: 'Search',
humans: humans
});
}
});
}
I have a button on my main page with the ID of search. I want to make it so that whenever someone clicks my search button, it queries the database and returns the results at localhost:1337/model/search. So far, I've tried sending an ajax request to that controller action with the two variables (criteria, value) but it doesn't work.
This is the ajax call that I am submitting:
$('#search').on('click', function() {
var criteria = $('#filter').val();
var value = $('#value').val();
$.ajax({
type: 'POST',
url: 'http://localhost:1337/human/search',
cache: false,
data: {
criteria: criteria,
value: value
},
success: function(data) {
console.log('SUCCESS!');
window.location.href = 'http://localhost:1337/human/search';
},
error: function(err) {
console.log('ERROR!');
}
});
});
And this is the corresponding view:
<table>
<thead>
<tr>
<th>ID</th>
<th width="150">First Name</th>
<th width="150">Last Name</th>
<th width="150">Contact</th>
<th width="150">E-Mail</th>
<th>View</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<% _.each(humans, function(model) { %>
<tr>
<td> <%= model.id %> </td>
<td> <%= model.firstName %> </td>
<td> <%= model.lastName %> </td>
<td> <%= model.contact %> </td>
<td> <%= model.email %> </td>
<td>VIEW</td>
<td>EDIT</td>
</tr>
<% }) %>
</tbody>
</table>
Promlem #1: When you search the model like this: Human.find().where({ criteria: value }), you actually search by field named "criteria", instead of searching by field, which name is held in criteria variable.
Try to create search object like this:
var searchObj = {};
searchObj[criteria] = value;
// and then search like you did before
Human.find().where(searchObj).done(function(err, humans) {
if(err) {
console.log('Error:' + err);
// you should return some response here:
res.send(err, 500);
}else{
res.view({
title: 'Search',
humans: humans
});
}
});
Problem #2: why you do ajax request and then do redirect to the same url?
First, you make POST request, although GET request is more suitable for search pupposes. POST is usually used when you create resources.
Second, in ajax success handler, after you receive the view with found humans models, you just redirect browser to http://localhost:1337/human/search url without any parameters passed, so your controller will try to search by empty value and criteria Human.find().where({ "": "" }). So you'll not see expected result.
It's not clear whether you want to get data via ajax, or just to show it in new HTML page?
EDIT: If you don't want to use ajax, let the HTML form do the work for you:
<form action="human/search">
<input name="criteria" value="foo">
<input name="value" value="bar">
<button type="submit" id="search">Search</button>
</form>
The search button click will submit the form and pass all form data in the GET request's query string: http://localhost:1337/human/search?criteria=foo&value=bar
Of course, you can build query string manually with javascript, without using form, and redirect browser to that url. Result will be the same.