send click count to django view using ajax - javascript

I am trying to send click id of item to Django view on every click so that I can update count against every item.
I achieved this by using ajax and javscript but there is some issue when id is sending id to Django view.
what actually happening-
when I click on any item(1)(first time) - nothing happen
but when I click on any item(let suppose 2) - then it send 1 and 2
again when I click on item 3 - it send 1,2,3
I don't know why it is behaving like this.
it should send only one item it which is clicked
my code is-
{% for solution in item %}
<ul>
<li >{{solution.solution_name}}
<a href="#"><i value="{{solution.id}}" class="fa fa-download down" aria-hidden="true" onclick="count(document.getElementById('fname_{{solution.id}}').value)">
<input type="text" id="fname_{{solution.id}}" value="{{solution.id}}"></i></a>
</li>
</ul>
{% endfor %}
my ajax part-
<script>
function count(a) {
var id = parseInt(a);
$('.down').click(function(e){
console.log("clicked item id is")
e.preventDefault();
console.log(id);
$.ajax({
type:'POST',
url: '/solutions/count',
data: {
'id': id
},
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert("A user with this username already exists.");
}
}
});
})
}
</script>

You are calling your function on click and in that function you got another click event, this will create you problems, so you need only one click event
use:
<script>
$(function(){
$('.down').click(function(e){
e.preventDefault();
var id = $(this).attr('value');
$.ajax({
type:'POST',
url: '/solutions/count',
data: {
'id': id
},
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert("A user with this username already exists.");
}
}
});
})
});
Remove the onclick attribute form your html

Related

JQUERY: Accessing element cousin by class

Hi I have the following html code:
<li class="grey">
<div class="row">
<button id="test" style="width:50%;" class="btn btn-blue-white cartBtn">Add to Cart</button>
</div>
<div class="row">
Go To Checkout
</div>
</li>
When I load the page, I hide the checkout link button until the user clicks "add to cart". After they click add to cart my javascript looks like this:
$('.cartBtn').click(function () {
//do stuff for preprocessing
var url = "../Store/AddToCart";
$.ajax({
type: "GET",
url: url,
data: {
//add data
},
dataType: "json",
success: function (data) {
if (data.success == true) {
$(this).closest('li').find('.checkoutLink').show();
}
}
});
});
the link never shows back up. I have also tried using
$(this).parent().parent().find('.checkoutLink').show()
as well and had no luck. How do i use jquery to get this anchor tag and make it visible.
The problem is this, when called from within the success function it no longer refers to the outer this. Create a variable outside of Ajax that refers to the original this.
$('.cartBtn').click(function () {
var $this = $(this);
//do stuff for preprocessing
var url = "../Store/AddToCart";
$.ajax({
type: "GET",
url: url,
data: {
//add data
},
dataType: "json",
success: function (data) {
if (data.success == true) {
$this.closest('li').find('.checkoutLink').show();
}
}
});
});

Too many ajax calls when form selections change

My webpage has two main sections: (1) search criteria (selection boxes in a form) used to access database information, and (2) a div in which the results are displayed. When the page loads initially, default values in the form are serialized and sent via ajax to php and the results are rendered. This results section is paginated to display all the results by clicking next, previous, etc. This all works perfectly.
Here’s the problem: each time the user makes a change to the criteria and the form’s data is serialized and sent via ajax, another layer of results is added somehow. When paginating through the results, it processes page 2 for each of the “layers” but only the last one that arrives from the server is displayed on the webpage. So, every time another change is made, another layer is added. Since ajax is asynchronous, the results displayed may or may not be the correct “layer.”
HTML:
<form id='submitCriteria' action='' method='post'>
<select id='selLevel' class='selectpicker' name='levels'>
<option title='Levels' value='No Preference'
selected = 'selected'>No Preference</option>
<option title='Levels:<br> 1+' value=1 >1+ </option>
<option title='Levels:<br> 2+' value=2 >2+ </option>
<option title='Levels:<br> 3+' value=3 >3+ </option>
</select>
</form>
<!-- Pagination: -->
<div id="spinnerDet" class="spinnerA">
</div>
<div id="paginationdiv">
<div id="pagination_container">
<div class="pagination">
<ul><li class="inactive">Previous</li>
<li class="pagerange">
<span class="total" a=" 58">
Page 1 of 58 </span></li>
<li p="2" class="active">Next</li>
</ul>
</div>
<!-- Output from server: -->
<table>
<tr><td>Levels</td><td>3</td></tr>
</table>
</div>
</div>
javascript/jQuery:
$("#submitCriteria").change(function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
type: 'post',
data: $("#submitCriteria").serialize(),
url: "/load_plans.php",
success: function(data) {
paginateDetails (data)
},
});
return false;
});
function paginateDetails (data) {
selDetails = JSON.parse(data);
var levels = selDetails.levels;
var totalsline = "Number of levels: " + levels;
$('#numResults').removeClass('spinnerA');
$('#numResults').addClass('stop-spin');
$('#numResults').html(totalsline);
loadData(1); //initial output based on default values
// Pagination buttons event:
$('#paginationdiv').on('click touchend',
'#pagination_container .pagination li.active', function (e) {
e.stopPropagation();
e.preventDefault();
var page = $(this).attr('p');
loadData(page);
});
function loadData(page) {
$.ajax({
type: "POST",
data: eval("'page=' + page + '&levels=' + levels"),
url: "loadDetails.php",
success: function (msg) {
$("#pagination_container").ajaxComplete(function (event, request, settings) {
$("#pagination_container").html(msg);
});
}
});
}
}
How do I eliminate another “layer” when selections in the form are changed/updated?
I think the problem is with the structure of your code, in this case you shouldn't be nesting the functions. Also you are repeatedly attaching click event to #paginationdiv (does it get removed and reatached when you reload data? You should use class instead of div in that case).
Without trying the code, i believe your problem might be caused by your loadData function - in your success callback you don't need to hook ajax complete again, success is called when your request is complete and successfull. I believe that part of your code was triggering twice ( on success and when ajaxComplete fired)
Your refactored code should look something like this:
$("#submitCriteria").change(function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
type: 'post',
data: $("#submitCriteria").serialize(),
url: "/load_plans.php",
success: function(data) {
paginateDetails (data)
},
});
return false;
});
function loadData(page) {
$.ajax({
type: "POST",
data: eval("'page=' + page + '&levels=' + levels"),
url: "loadDetails.php",
success: function (msg) {
//$("#pagination_container").ajaxComplete(function (event, request, settings) {
$("#pagination_container").html(msg);
//});
}
});
}
function paginateDetails (data) {
selDetails = JSON.parse(data);
var levels = selDetails.levels;
var totalsline = "Number of levels: " + levels;
$('#numResults').removeClass('spinnerA');
$('#numResults').addClass('stop-spin');
$('#numResults').html(totalsline);
loadData(1); //initial output based on default values
// remove previous click handlers
$('#paginationdiv').off()
// Pagination buttons event:
$('#paginationdiv').on('click touchend',
'#pagination_container .pagination li.active', function (e) {
e.stopPropagation();
e.preventDefault();
var page = $(this).attr('p');
loadData(page);
});
}

How to generate a button with its own js function?

Well I have data retrieved from ajax, I need to parse it in order to generate inputs with different <input> values. While clicking on <a> that should get near standing input value and go to ajax
<script type="text/javascript">
function proceed() {
var ID = document.getElementById('btnid').value;//probably that`s the wort way, because all of `<a>` buttons would have same id
//ajax with ID to proceed further
}
$.ajax({
async: false,
type: "POST",
url: "../api/",
data: {'data': "mydata"},
dataType: 'JSON',
complete: function (res) {
for(var i = 0; i < 10; i++) {
document.getElementById('nie').innerHTML = "
<ul class=\"somec\">
<li class=\"liclass\">
</input id=\"btnid\" value=\""+res.response[i].animal+"\" class=\"thatclass\" onclick=\"proceed();\"></input>//different values
<a id="clicker" onclick="proceed()"></a>//clickable link
</li>
</ul>
";
}
});
</script>
<html>
<div id="nie">
</div>
</html>
Any help or advises for solution ?
You cannot have more than one id in a single DOM -- only one unique id is allowed. Since jQuery is used here, you can take advantages of the other methods and API it provides.
First of all, I would move the loop to success handler of $.ajax because that ensures that I have data returned from the server.
As for "appending" input and anchor pairs, use $.append. What you're currently doing is just updating #nie with the last element's data in the loop.
For events, delegate the clicks on anchors. This is better because you might continue adding more elements, so you have to go through binding them to an event.
And please, don't set async to false in $.ajax settings. This has unexpected results and makes the browser slow to point that freezes and crashes. jQuery ajax async: false causes a strange warning?
$(function(){
var $nie = $('#nie');
// Delegate the click event
$(document).on('click', '.clicker' function(){
var id = $(this).siblings('input').val();
// Use id in upcoming AJAX request.
});
$.ajax({
type: "POST",
url: "../api/",
data: {'data': "mydata"},
dataType: 'JSON',
success: function (res){
$.each(res.response, function(i, r){
$nie.appeand('<ul class="somec">\
<li class="liclass">\
<input value="'+ r.animal+ '" class="thatclass"/>\
<a class="clicker"></a>\
</li>\
</ul>');
});
}
});
});

Send id with ajax and jquery

Today I have a problem sending id with ajax and jquery ,I have a foreach in the view of laravel like this ,
<div class="ident" id="auctionIdentifier-{{$i}}" auction="{{$auction->id}}"></div>
this in the elements recieve correctly the id of auctions but when I try to doing a click I only send the first id.
I don't know when I doing a click in the next bid , I don't send the id corresponding.
id}}">
$(".inscription").click(function(){
console.log($(".ident").attr('auction'));
$.ajax({
url:'../bid/inscription',
dataType:'json',
type:'get',
cache:true,
success: function (response) {
console.log("ok");
},
});
});
Maybe this helps:
$(".ident").click(function(){
var id = $(this).attr('auction');
$.ajax({
url:'../bid/inscription',
dataType:'json',
type:'get',
cache:true,
data: {
id: id
},
success: function (response) {
console.log("ok");
},
});
});
Basically you need to get the currently clicked element auction attribute. Also you might want to add data- in front of it like so: data-auction="VALUE". This way you can get it with $(el).data('auction').

PHP foreach loop and one AJAX call for each of the loop

This question has already been asked here, but I could see any of the answers working for me.
I have the following code in Laravel 4:
<ul class="list-group">
#foreach($inboxMsg as $inbox)
<li class="list-group-item no-border">
<a href="#{{ $inbox->mid }}" id="fragment1g">
<span class="no-margin sender center-block"><b>John Doe</b>
<small class="pull-right datestamp"><strong>2:00AM</strong></small>
</span>
<span>
<strong>{{ $inbox->subject }}</strong> <i class="fa fa-paperclip att"> 3</i>
</span>
</a>
</li>
#endforeach
</ul>
As you can see I am passing the ID of each message in the URL with # to prevent page reload and in my AJAX I tried to get the value after # (hash). Here is my AJAX
<script type="text/javascript">
$(document).ready(function(){
$('.list-group-item a').click(function (event) {
//Check if the URL has value after hash
if(window.location.hash) {
//set the value as a variable, and remove the #
var hash_value = window.location.hash.replace('#', '');
//show loader
$('#loader').fadeIn("slow");
//Proccess data through Ajax
$.ajax({
type: "POST",
url: "{{ URL::route('post-read') }}",
data: { mid : hash_value },
cache: false,
dataTye: "json",
success: function(data)
{
$('#loader').fadeOut("slow");
alert(data["body"]);
}
});;
}
});
})
</script>
With this code it is working but not correctly. It forces me to click twice before alerting the body of the message, and when I click the second message it first brings the body of the first message, until I click it again before I could see the body of second message. But without this line of Jquery "$('.list-group-item a').click(function (event){" the ID is passed in the URL after # (hash) but AJAX call does not work.
Is there any other way to do this?
use event.preventDefault(); to prevent page reload after clicking on link
you can directly take $inbox->mid using attribute using some data attribute
<a data-id="{{ $inbox->mid }}" id="fragment1g">
<span class="no-margin sender center-block"><b>John Doe</b>
<small class="pull-right datestamp"><strong>2:00AM</strong>
</small>
</span>
<span>
<strong>{{ $inbox->subject }}</strong> <i class="fa fa-paperclip att"> 3</i>
</span>
</a>
<script type="text/javascript">
$(document).ready(function(){
$('.list-group-item a').click(function (event) {
event.preventDefault();
var hash_value = $(this).attr("data-id");
//show loader
$('#loader').fadeIn("slow");
//Proccess data through Ajax
$.ajax({
type: "POST",
url: "{{ URL::route('post-read') }}",
data: { mid : hash_value },
cache: false,
dataTye: "json",
success: function(data)
{
$('#loader').fadeOut("slow");
alert(data["body"]);
}
});
});
})
</script>
Dont use the window.location.hash. You sholud put the right url in the element and use event.preventDefault();
PHP:
<a href="{{ URL::route('post-read', array('mid'=>$inbox->mid)) }}">
JS:
event.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr('href'),
cache: false,
dataTye: "json",
success: function(data)
{
$('#loader').fadeOut("slow");
alert(data["body"]);
}
});;

Categories

Resources