0

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>
3
  • It is possible with jquery/ajax. But looking at the template I have question, if you dont want to use forms then why have it in first place? Commented Jun 14, 2016 at 11:45
  • since i have input type 'submit' i have used forms Commented Jun 14, 2016 at 11:57
  • In that case, as @Loic suggested use serialize method of form in javascript to get all the form field values and make ajax call. But, you will have to stop default form submit for it to work, I guess you must be aware of it. Commented Jun 14, 2016 at 12:06

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.