update a element with jquery - javascript

Hi i have a id of #item_quantity in a span. once a button is clicked with and id of #update_cart. I want the span to refresh its contents. the target data would have already been updated on the click also that works, but cant seem to get the span to update its data.
i am using the following script to try refresh it:
the link i m targeting was the same page i was on. Once a product is added to the cart, and the page is refreshed, then the list updates, so i thought i could right a scripts that just refreshes that div once something is clicked and all will be done. but it does nothing.
script
$(function() {
$("#update_cart").click(function(evt) {
$("#item_quantity").load("http://apecenergy.co.uk/products.php?p=4")
evt.preventDefault();
})
});
html
<div class="menu_cart_units "><span class="" id="item_quantity">
<cms:number_format quantity decimal_precision='0'/></span>×</div>
<div class="menu_cart_option"><cms:show title /></div>
<div class="menu_cart_subtotal"><span class="" id="item_price"> £<cms:number_format line_total /></span></div>
json
"id": <cms:show id/>,
"quantity": <cms:show quantity/>,
"price": <cms:show price/>,
"line_total": <cms:show line_total/>,
"requires_shipping": <cms:if requires_shipping>true<cms:else/>false</cms:if>,
"name": "<cms:show name/>",
"title": "<cms:addslashes><cms:show title/></cms:addslashes>",
"link": "<cms:show link/>",
"remove_item_link": "<cms:pp_remove_item_link/>",
"line_id": "<cms:show line_id/>",
If i go down the ajax json method, there will be multiple ids which relate to different products, from each id i require quantity, name and line total, to be updated in the div.

what data your request returns??
$("#item_quantity").load("http://apecenergy.co.uk/products.php?p=4")
Assuming the user returns valid JSON i would say a simply "success" with count of items as [{'result':'success'},{'count','<count>'}] if items updated in cart successfully else return something like [{'result':'error'}]! this should be simple as
making ajax call with jquery:
$.ajax({
type:"POST",
url:'Your url that return JSON encoded success with Count of items or Error message',
data:'item id to update here 4 i guess or post Data'
datatype:"JSON",
success:function(data)
{
var tmp=Jquery.parseJSON(data);
switch(data.result)
{
case 'success':
$('#item_quantity').text(data.count); //update the span
break;
case 'error':
alert('something went Wrong');
break;
default:
alert('error');
break;
}
},
error:function()
{
alert('Ajax Request Failed');
}
});

// parse the JSON into a javascript object
var cart_items = JSON.parse(json);
// matches all items in the cart_items list, which have the id == 30
// filter returns an array of matched items
var matching_items = cart_items.filter(
function (item) {
if (item.id == 30) {
return item;
}
});
// since it should only match one item, we take the first element of the array
var item = matching_items[0];
// print out the items quantity
console.log(item.quantity);

Related

How to perform .delete() queryset in Django in a ListView?

Here is what I've done so far:
1.) I've made a javascript function that gets all the id's of the items (using checkbox select) in the database like so (this is DataTables):
function () {
// count check used for checking selected items.
var count = table.rows( { selected: true } ).count();
// Count check.
// Count must be greater than 0 to delete an item.
// if count <= 0, delete functionality won't continue.
if (count > 0) {
var data = table.rows( { selected: true } ).data();
var list = [];
for (var i=0; i < data.length ;i++){
// alert(data[i][2]);
list.push(data[i][2]);
}
var sData = list.join();
// alert(sData)
document.getElementById('delete_items_list').value = sData;
}
}
It outputs something like 1,2,5,7 depending on what rows I have selected.
2.) Passed the values inside a <input type="hidden">.
Now, I've read a post that says you can delete data in Django database using a checkbox, but I'm not sure how exactly can I use this.
I'm guessing I should put it in the ListView that I made, but how can I do that when I click the "Delete selected items" button, I can follow this answer?
I'm trying to achieve what Django Admin looks like when you delete items.
My ListView looks like this:
Yes you can use linked example. Django Admin do it the same way, You send selected ids and django do filtering by given values and after django apply selected action for selected items.
UPDATE
For example.
class List(ListView);
def post(self, request, *args, **kwargs):
ids = self.request.POST.get('ids', "")
# ids if string like "1,2,3,4"
ids = ids.split(",")
try:
# Check ids are valid numbers
ids = map(int, ids)
except ValueError as e:
return JsonResponse(status=400)
# delete items
self.model.objects.filter(id__in=ids).delete()
return JsonResponse({"status": "ok"}, status=204)
And html:
<button id="delete-button">Del</button>
<div id="items-table">
{% for object in objects_list %}
<div class="item" data-id="{{object.id}}">{{ object.name }}</div>
{% endfor %}
</div>
<script>
$(function(){
$('#delete-button').on('click', function(e) {
// Get selected items. You should update it according to your template structure.
var ids = $.map($('#items-table item'), function(item) {
return $(item).data('id')
}).join(',');
$.ajax({
type: 'POST',
url: window.location.href ,
data: {'ids': ids},
success: function (res) {
// Update page
window.location.href = window.location.href;
},
error: function () {
// Display message or something else
}
});
})
})();
</script>

Populate data from groovy controller in pop up

I have a gsp page with a delete button for each row of a table. On the button click I want a pop up which tells the consequences of the delete. These consequences depends on the data present in the row and a few other constraints known to the grails service which is called from the grails controller associated to the gsp page. If the user confirms these consequences the row should be deleted from the table, else the table remains unchanged.
How should i go about to achieve this behavior?
Currently, I have in my gsp
<tr>
<td>name</td>
<td>parentName</td>
<td>data</td>
<td>
<g:link action="deleteRow" params="${[name: row.name, parentName: row.parentName]}">
<button class="deleteSnapshot">Delete</button>
</g:link>
</td>
</tr>
and in my .js file
$(document).on('click', ':button', function (e) {
var btn = $(e.target);
btn.attr("disabled", "disabled"); // disable button
alert('getting deletion details');
//var deletionDetails -->not sure how to get these
//var deletionDetails will get data from controller action:"getDetails"
if (confirm('/*print deletion details and ask*/ Do you want to proceed?')) {
alert('will delete')
return true
}
else {
btn.removeAttr("disabled"); // enable button
return false
}
});
and in my controller
class DeleteController{
DeleteService deleteService
def index() {
[list:deleteService.getTableList()]
}
def getDeletionDetails(string name, String parentName){
return deleteService.getDetails(name,parentName)
}
def deleteRow(String name, String parentName){
service.deleteRow(name, parentName)
redirect controller:"DeleteController", action:"index"
}
}
I know the deletion works fine, because it works even with in the current state. Just that the confirmation box asks Do you want to proceed, without displaying the details.
Any help on how i could achieve what I am looking for will be appreciated.
P.S. I am new to stackoverflow, so if i missed out on certain convention do let me know.
Thanks in advance.
I can think of two ways of doing it:
The first one is using ajax to both get deletion details and delete the row
Assuming that deleteService.getDetails(name, parentName) returns a String,
first you need to change an getDeletionDetails action so it renders the response:
def getDeletionDetails(String name, String parentName){
render deleteService.getDetails(name, parentName)
}
and change g:link-s to buttons in gsp:
<button data-name="${row.name}" data-parent-name="${row.parentName}">
Delete
</button>
In your .js then put:
$(document).on('click', ':button', function (e) {
var btn = $(e.target);
btn.attr("disabled", "disabled"); // disable button
var name = btn.data('name');
var parentName = btn.data('parentName');
$.ajax({
url: "/delete/getDeletionDetails",
data: {
name: name,
parentName: parentName
},
success: function (data) {
if (confirm(data + '\nDo you want to proceed?')) {
$.ajax({
url: '/delete/deleteRow',
data: {
name: name,
parentName: parentName
},
success: function (d) {
console.log("Success: " + d);
}
});
} else {
btn.removeAttr("disabled"); // enable button
}
}
});
});
What this code does is it sends an ajax call to /delete/getDeletionDetails, then uses its response (rendered by getDeletionDetails action in DeleteController) to show a confirmation alert. If user confirms the question, another ajax call is sent - now to deleteRow action of DeleteController - with parameters taken from data attributes of clicked button. If user cancels - nothing happens, except for reenabling a button.
Your deleteRow should only change the return statement - it also must render the response:
def deleteRow(String name, String parentName){
service.deleteRow(name, parentName)
render "You deleted an item $name - $parentName."
}
You don't need redirect here, because - thanks to using ajax - user will never leave delete/index. You can just display some kind of confirmation on page after successful ajax call.
The second option is to put deletion details in hidden fields or data- attributes in each row and then just retrieve them in js:
You can create a method getDeletionDetails() in row's domain class (presumably Row) that returns the details (using services in domain classes is not perfect, but is should work ok if the service is not very complex). Then, in your .gsp place:
<td>
<g:link action="deleteRow" params="${[name: row.name, parentName: row.parentName]}">
<button class="deleteSnapshot" data-details="${row.deletionDetails}">Delete</button>
</g:link>
</td>
You should then be able to get details in .js like this:
var deletionDetails = btn.data('details');

Make a query with JSON

I have JSON data gets Vedios data of youtube list. And the following link display structure of my JSON.
<a href="https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=UUbW18JZRgko_mOGm5er8Yzg&key=AIzaSyDGm1uzuqPPUGzG-qN7u6gTaS8ApXBJYvw">
Click me to get all list videos ID ...
</a>
And here is the channel with its ID
After analyses of my JASON, I have JSON array named "items" (row 9).
Now all I need to get specific information from all units included with this array "items".
All I need to make a query using JavaScript or c# to return JSON with this specific data
title
description
thumbnails - standard
videoId
Finally, I found a solution for my problem. Not very professional but good for now.
I used Jquery selectors to extract data from my JSON object as following.
$(document).ready(function () {
var jsonLink = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PL0zTBP9-UnPaIurxKLr3rfPZwHrFl2mEq&key=AIzaSyDGm1uzuqPPUGzG-qN7u6gTaS8ApXBJYvw&maxResults=50";
$.getJSON(jsonLink).done(function (data) {
var items = [];
$.each(data.items, function (i, item) {
items.push("<li>" + item.snippet.title + "</li>");
if (i === 5) {
return false;
}
});
$("<ul/>", {
"class": "my-new-list",
html: items.join("")
}).appendTo("body");
});
});

load part of the html page when filtering results with ajax

I want to filter a search results using 3 checkboxs. The results are presented in the div with the id=posts_results
<div class="checkbox">
<label><input type="checkbox" id="id1" class="typePost" value="En groupe"> val1 </label>
</div>
<div class="checkbox">
<label><input type="checkbox" id="id2" class="typePost" value="En groupe"> val2 </label>
</div>
<div class="checkbox">
<label><input type="checkbox" id="id3" class="typePost" value="A domicile"> val3</label>
</div>
<div class="checkbox">
<label><input type="checkbox" id="id4" class="typePost" value="Par webcam"> val4</label>
</div>
<div id="posts_results">
{% include 'posts/posts_results.html' %}
</div>
<script>
$('.typePost').change(function (request, response) {
var v1=$('#id1').is(":checked")? 1:0;
var V2=$('#id2').is(":checked")? 1:0;
var V3=$('#id3').is(":checked")? 1:0;
var v4=$('#id4').is(":checked")? 1:0;
$.ajax({
url: '/posts/type_lesson/',
dataType: 'json',
type: "GET",
data: {
group: groupChecked,
webcam: webcamChecked,
home: homeChecked,
move: moveChecked,
distance: distance,
},
success: function (object_list) {
$('#posts_results').load("my_page.html", object_list);
alert('after')
}
});
});
<script>
this is my url:
url(r'^filter/$', views.filter, name='filter_type_lesson'),
and this is my view:
def filter(request):
if request.method=='GET':
#as an exemple I'll send all posts
data= PostFullSerializer(Post.objects.all(), many=True)
return JsonResponse(data.data, safe=False)
The filter function excute some filters according to the json sent data, serialize the filtered posts and send them back (in this case I send all the posts as an example).
The results are displayed using a forloop in the div with id "posts_results" and the html is in the file posts_results.html.
The json data are sent but the ajax success function does not update or load the div
and it is also possible to stay
I like to stay away from raw POST data as much as possible and let the forms API do the heavy lifting. You can do what you have already with a lot less code in a much more secure way.
Make a form with four BooleanFields named for the BooleanFields in your model. You can override how they are displayed in the HTML with the label variable.
class TheForm(forms.Form):
my_field = forms.BooleanField(required=False, label="What I want it to say")
my_field2 = forms.BooleanField(required=False, label="What I want it to say 2", help_text="Something else")
my_field3 = forms.BooleanField(required=False, label="What I want it to say 3", help_text="Something else")
Output as <form class="my_form">{% csrf_token %}{{form.as_table}}</form>
Submit it with JS like this:
$('.my_form input[type=checkbox]').change(function(e){
e.preventDefault()
$.post('module/filer/', $('.my_form').serialize(), function(data) {
// Handle data
});
});
When the form is submitted and validated take the cleaned_data attribute and filter your models like this
models = Post.objets.filter(**form.cleaned_data)
This will work because the form fields and named the same as the fields in your model. The same as doing Post.objects.filter(my_field=True, my_field2=True, my_field3=False). Then you can do whatever you want with it. I would use a FormView to do all this:
class MyView(FormView):
form_class = TheForm
def form_valid(self, form):
models = Post.objets.filter(**form.cleaned_data)
data= PostFullSerializer(data, many=True)
return JsonResponse(data.data, safe=False)
Now nothing is going to update the div by itself. It is only created when the HTML is initially requested. In your success function you'll need to append your elements manually like this:
$('.my_form input[type=checkbox]').change(function(e){
e.preventDefault()
$.post('module/filer/', $('.my_form').serialize(), function(data) {
var post_results = $('#post_results').html(''); // Clear out old html
$.each(data, function(item) {
// Create new divs from ajax data and append it to main div
var div = $('<div>');
div.append($('<div>').html(item.my_field));
div.append($('<div>').html(item.my_field2).addClass('something'));
div.appendTo(post_results);
});
});
});
You can also just past rendered HTML through ajax and do $('#post_results').html(data);. Instead of calling json response you would call self.render_to_response on the FormView.
maybe you could try to render the template in your view and then load the rendered data in your div.
Supposing your posts/posts_results.html is some as:
<ul>
{% for post in posts %}
<li> Post: {{post.name }} / Author: {{post.author}} / Date: {{post.created_at}}</li>
{% endid %}
<ul>
In your view, at the moment when you do respective actions, you can render the template and add the html content to the response, ie (based un your current code):
def filter(request):
if request.method=='GET':
json_data = {
"success": False,
"message": "Some message",
"result": "some result",
}
posts = Post.object.all()
template = "posts/posts_results.html"
things_to_render_in_your_template = {
"posts": posts, # you can add other objects that you need to render in your template
}
my_html = get_template(template)
html_content = my_html.render(things_to_render_in_your_template)
# here the html content rendered is added to your response
json_data["html_content"] = html_content
json_data["success"] = True
return JsonResponse(json_data)
Then in your JS, at the momento to check ajsx response, you can add the rendered content into your div
$.ajax({
url: '/posts/type_lesson/',
dataType: 'json',
type: "GET",
data: {
group: groupChecked,
webcam: webcamChecked,
home: homeChecked,
move: moveChecked,
distance: distance,
},
success: function (response) {
# response is the json returned from the view, each key defined in your json_data dict in the view, is a key here too
# now insert the rendered content in the div
$('#posts_results').html(response["html_content"]);
alert('after');
}
});
I suggest you instead of create one by one data to your ajax request, use serialize method of jquery or create a FormData object, also instead of GET, use POST to do your request more safe

Update ng-repeat values in angular js

I am listing some elements and each element has a click event and as a parameter the same element.
<a class="item item-avatar item-lista" ng-click="verView({{$index}},{{view}})">
Function verView :
$scope.verView = function(index,view){
sessionService.set("view_leido",view);
$location.path("/event/view/"+index);
}
Function darLike:
$scope.darLike = function(view_id, index){
console.log(UrlService.url+'likeView/'+sessionService.get("user_id")+'/'+sessionService.get("hash")+"/"+view_id+"/");
$http({method: 'GET', url: UrlService.url+'likeView/'+sessionService.get("user_id")+'/'+sessionService.get("hash")+"/"+view_id+"/"})
.success(function(data){
if(data.status == 1){
angular.copy(data.view.TableView, $scope.views[index]);
}
})
.error(function(){
})
.finally(function(){
});
}
These elements can be given LIKE this creates a record in my database and return the number of Likes having my element, so I update my object in the list. But while sending object parameter arrives outdated, for example:
If you would LIKE to one that has 0 likes, stay at 1 like, when you click and view detail I get 0 likes yet.

Categories

Resources