0

I need to implement AJAX and its working fine. However, I am having problem in applying ajax to each instance of a model. It's just being applied on the top Object and applying ajax call on the same page. For remaining objects, when I click on the link its directing me to new page and showing me JSON objects which I dont want.

Views.py

def upvote(request, post_id):

if request.method == "POST":
    p = get_object_or_404(Post, pk=post_id)
    p.upvote += 1
    p.save()
    return JsonResponse({'count':p.upvote })

if request.method == "GET":
    p = get_object_or_404(Post, pk=post_id)
    p.upvote += 1
    p.save()
    data = {
        'count' : p.upvote,
    }
    return JsonResponse({'count': p.upvote})

Urls.py

url(r'^(?P<post_id>[0-9]+)/upvote/$', views.upvote, name='upvote-detail'),

Views.html

<script>
    $(function(){
       $('#up_vote').click(function(e) {
          e.preventDefault();
          window.alert("hello");
          console.log("hello");


          $.ajax({
            url: $(this).attr('href'),
            type :'get' ,
            success : function (data){
              // alert('success');
              $('#upvote_count').html(data.count);
            },
            failure : function (data){
              alert('failure') ; 
            }
          }) ;  // ajax call 

       }); // upvote link call
</script>

<div id="columns">
    {% for post in object_list %}

        <div class="pin">
            <a href="/posts/{{ post.id }}/">

            <img src= "/static/media/{{post.image}}" />
            </a>
            <p>
                {{post.description}}
                (<a href="{% url "post-edit" pk=post.id %}">edit</a>)
            </p>


            <div style="float:left">
              <a href='{% url 'upvote-detail' post.id %}' id='up_vote'>Up vote  </a>
              <span id='upvote_count'> {{ post.upvote }} </span> 
            </div>


            <div style="float:right">
              <a href='{% url 'downvote-detail' post.id %}' id='down_vote'> Down vote </a>
              <span id='downvote_count'>{{post.downvote}}</span>
            </div>


        </div>
    {% endfor %}

    </div>

Here is my all the files. Currently AJAX call is working absolutely fine. Its just applying on the top (first) of object in for LOOP. For Remaining objects, when I click on link, it render me to new page. Could someone identify the problem? Thanks,

user3487775
  • 147
  • 9
  • 1
    basically return a `JsonResponse`, a complete answer on how to implement ajax would be too broad for stack overflow, it is already shown in the documentation too – Sayse Jul 22 '15 at 07:31
  • @Sayse Can you tell me where I can find documentation? or any helpful link – user3487775 Jul 22 '15 at 07:44
  • 1
    It took me about 15 seconds to find [the answer on SO](http://stackoverflow.com/a/20307569/5098707). Please, do some research before asking. – Ernest Jul 22 '15 at 07:56
  • https://docs.djangoproject.com/en/1.8/topics/class-based-views/generic-editing/#ajax-example – madzohan Jul 22 '15 at 07:57

2 Answers2

1

in views.py

def detail(request):
    return render(request, 'detail.html', {'posts': Post.objects.all()})

def upvote(request, post_id):
   if request.method == "POST":
       p = get_object_or_404(Post, pk=post_id)
       p.upvote += 1
       p.save()
       return JsonResponse({'count':p.upvote })
   return JsonResponse({})

in detail.html:

{% for post in posts %}
     <a href='{% url 'upvote-detail' post.id %}' id='up_voite'>Up voite <span id='voite_count'> {{ post.upvote }} </span> </a>
 {% endfor %}

<script>
    $(function(){
       $('#up_voite').click(function(e) {
          e.preventDefault();
          $.post($(this).attr('href'), function(data) {
              $(this).find('span').html(data.upvote);
          });
       });
    });
</script>

code is not checked

comalex3
  • 2,497
  • 4
  • 26
  • 47
0

Try this:

def upvote(request, post_id):
    p = get_object_or_404(Post, pk=post_id)
    errors = []
    data = {}
    try:
        p.upvote += 1
        p.save()
        data = {
            'success': 1,
        }
    except:
        errors.append(['There was an error'])
        data = {
            'success': 0,
            'errors':errors,
        }
    return HttpResponse(json.dumps(data))
chandu
  • 1,053
  • 9
  • 18