Home > Software design >  update data with href link in django and ajax
update data with href link in django and ajax

Time:06-24

$("#feedlikes").on("click", function(e){
        e.preventDefault();
        $.ajax({
            type: 'get',
            url:'{% url "feedlikes" %}',
            data:{},
            success: function({
                alert("Updated Successfully")
            }),
        }),
    }),

those are my Ajax code help me to get them work. this is my view:

def feedlikes(request, feed_id):
    feed_update= Feeds.objects.get(pk=feed_id)
    feed_update.likes = feed_update.likes  1
    feed_update.save()

CodePudding user response:

If you need to update the data you need to pass post method in ajax with csrf_token in headers.

$("#feedlikes").on("click", function(e){
        e.preventDefault();
        $.ajax({
            type: 'post',
            url:'{% url "feedlikes" %}',
            data:{},
            headers: {
                'X-CSRF-Token': {{csrf_token}}
            },
            success: function({
                alert("Updated Successfully")
            }),
        }),
    }),

CodePudding user response:

your feedlikes function expect feed_id but you are not supplying in the ajax url. Your ajax url should be

url:'{% url "feedlikes" feed_id=1 %}'

The problem: how to get that feed id in ajax?

You can make a hidden html tag with id equal to #feedlikes-id (eg feedlikes-1) inside #feedlike div or something like that and access just above submitting ajax and store in some variable and set to url then submit.

  • Related