Toto Briac
Toto Briac

Reputation: 936

My AJAX is working and I want to know why

In my app I made a favorite list that a user can populate using AJAX. Is it working perfectly but I am not sure if I did it the right way and I would like to know how to do it the proper way. Or maybe somehow I did it right.

My html:

<div class='sub_button'>            
                    <form class="add_btn" method='post'>{% csrf_token %}
                    <button class='added btn' value= '{{product.id }} {{ sub_product.id }}' ><i class=' fas fa-save'></i></button>                            
    </div>

My AJAX:

$(".row").on('click', ".added", function(event) {
    let addedBtn = $(this);
    console.log(addedBtn)
    event.preventDefault();        
    var product = $(this).val();
    var url = '/finder/add/';   
    $.ajax({        
        url: url,        
        type: "POST",
        data:{
            'product': product,            
            'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
        },
        datatype:'json',
        success: function(data) {
          if (data['success'])            
          addedBtn.hide();             
        }
    }); 
});

My views.py

def add(request):
    data = {'success': False} 
    if request.method=='POST':
        product = request.POST.get('product')
        user = request.user       
        splitted = product.split(' ')
        sub_product = Product.objects.get(pk=(splitted[1]))
        original_product = Product.objects.get(pk=(splitted[0]))       
        p = SavedProduct(username= user, sub_product=sub_product, original_product = original_product)
        p.save()        
        data['success'] = True
    return JsonResponse(data)

What is bugging me is the way I passed '{{product.id }} {{ sub_product.id }}'. Because I've made it after some tinkering.

Upvotes: 0

Views: 38

Answers (1)

Arun T
Arun T

Reputation: 1610

There is a better way to do this.

ie, if you have only one product.id and sub_product.id in this page instance. Then in a script tag at the end of the HTML template for this page you add the following:

<script>
    var product_id = {{ product.id }}
    var sub_product_id = {{ sub_product.id }}
</script>

Then you can link the external JS file in which you have AJAX to this HTML template with another script tag.

Now your product_id and sub_product_id will be available in your external JS script file in which you have the AJAX code.

So that way, you don't have to pass it through the value attribute of the button tag and things look more clean.

Upvotes: 1

Related Questions