[Fixed]-Unable to display information using ajax django

1๐Ÿ‘

โœ…

So what you are trying to do requires you to merge the AJAX response with a for-loop, so you would need it processed by Django. The only way to do this is to return a render() response instead of a JSONResponse, and then append that to your html. For example:

Create a new HTML file called _store-form.html:

<form id="form" action="{% url 'storeView'  user=store.user %}" method="post"  />
                  {% csrf_token %}          

                  <div class="increment">
                  {% for size in sizes %}

                  <strong class="pull-left">{{size}}:</strong> 
                  <input type = "number" name="quantity" value="{{product.quantity}}">
                  <input type = "hidden" name = "size" value="{{size}}">
                  <input type = "hidden" name = "productid" value = "                              {{product.id}}">
                   {% endfor %}
                  </div>
                  <input type="submit" value="submit" id="submit"/>
</form>

In your views.py, instead of the last line return JsonResponse(data):

return render(request, '_store-form.html', {'sizes': sizes})

and now amend your JS to append the new returned html into your page:

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

            error: function(response, error) {
                alert(error);  
            }
        });
    };
</script>
๐Ÿ‘คHybrid

0๐Ÿ‘

Django template variables are passed from views.py through the context, while ajax is fetching value from somewhere else. Django template variable and javascript variables are two different things, you cannot expect them to work together. You need to use javascript to render the form manually. Take a look at jquery doc for details.

๐Ÿ‘คShang Wang

Leave a comment