[Fixed]-Unable to send unique product id using jquery ajax

1👍

You really don’t seem to be requiring a form here. If you want to fetch some data based on productId clicked, just have an onclick listener on your hyperlink:

{% for product in products %}
    <a href = '#' onclick="getStoreView(e, {{ product.id }})">
    {{ product.id }}
    </a>
{% endfor %}

And then in your js, have that function:

<script type="text/javascript">
    function getStoreView(event, productId) {
        event.preventDefault();   
        console.log(fData);
        // Send productId as query param of url
        $.ajax({        
            type: "GET",
            url: "{% url 'storeView'  user=store.user %}",
            data: fData,
            success: function(data) {
                alert('success');
            },

            error: function(response, error) {
                alert(error);  
            }
        });
    });
</script>

0👍

Like Rohit commented, you should not use the same ID more than once on a page. Everytime your loop renders a product, it will print a form with the ID “productfrm”. You are using this as the selector for fData var and that is where your script goes wrong. jQuery does not know using this selector that you are looking for the form within the current product.

One thing you could do is remove the ID from the form. Then change

var fData = $("#productfrm").serialize();

to

var fData = $(this).find('form').serialize();

That should do the job. However, it is not good practice to put a form within an anchor tag.

Leave a comment