Kiran
Kiran

Reputation: 1531

How to send data to view without using html forms?

I have some data(checkbox and input field) in template file which I want to send to views.Due to page refresh upon submit checkbox field is unchecked.So how to send data to django view without using html form.Is it possible using jquery/ajax?

<form id="myform">
    {% csrf_token %}
    <p id=id3>Categories</p>
    {% for i in My_Cat %}
        <input type="checkbox" id="mycheck" name="cat_name" value="{{i.category}}">{{i.category}}<br>   
 <!--category is db column -->
 <!--My_Cat is the context from the view -->
    {% endfor %}

    <p>Price</p>
    &#8377;<input type="text" name="min_price" maxlength="4" size="3" >
    to &#8377;<input type="text" name="max_price" maxlength="4" size="3"><br> 
    <input type="submit" value="Go" style="margin-top: 6px;">
</form>

Upvotes: 0

Views: 1819

Answers (1)

Lo&#239;c
Lo&#239;c

Reputation: 11943

It is possible indeed.

Using javascript, catch the form submit event.

In the function, serialize the form (exemple using jquery : https://api.jquery.com/serialize/), or get the field values using selectors.

Craft your ajax request, then send it.

And on view side, don't render a template, use jsonresponse instead : https://docs.djangoproject.com/en/1.9/ref/request-response/#jsonresponse-objects

Upvotes: 1

Related Questions