Erik Åsland
Erik Åsland

Reputation: 9782

Django/Python: How to submit form once div is clicked using AJAX?

I want a <form> from class up-arrow-form to be submitted once the <div> from class up-arrow is clicked. The form contains an <input> tag that is type='hidden' that has the value {{i.id}} that I want passed to the view to be manipulated. How do I do this using Ajax?

Here is the relavant html from my template...

{% for i in post.posts %}
    <li>
        <div>
             <div class='up-arrow'>
                 <form class='up-arrow-form' action='voteupposts'>
                     <input type='hidden' value='{{i.id}}' name='post-id'>
                 </form>
             </div>
             {{i}}
        </div>
    </li>
{% endfor %}

Here is my jQuery/AJAX thus far...

$(document).ready(function(){
    $('.up-arrow').click(function(){
        $(this).hide()
        $('.up-arrow-form').submit(function(){
            $.get('voteuppost', $(this).serialize(), function(res){
            })
            return false
        })
    });
})

View...

class VoteUpPost(View):
    def get(self, request):
        print(request.GET.get('blaze'))
        return JsonResponse({'status': True})

URL route...

url(r'^voteuppost$', VoteUpPost.as_view()),

Upvotes: 0

Views: 521

Answers (1)

An0nC0d3r
An0nC0d3r

Reputation: 1303

Well, here's an example as to how I would normally use ajax to make a request (incorporating your code). Might not be exactly what you need, but should point you in the right direction...

$('.up-arrow').click(function(){
    $(this).hide()
    $('.up-arrow-form').submit(function(){

        $.ajax({
            url: 'http://someurl.com/voteuppost',
            type: 'GET'
            data: $(this).serialize(),
            success: function(data) {
                // do something on success
            },
            error: function(err) {
                console.log('err: ' + err);
            }
        });

    });
});

Upvotes: 1

Related Questions