Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit form without refreshing page using Django, Ajax, jQuery?

I am newbie working with django. I need simple example. How to submit form (post) without refreshing page using Django, Ajax, jQuery?

This is my form, views and template:

views.py

from django.shortcuts import *
from django.template import RequestContext
from linki.forms import *

def advert(request):
    if request.method == "POST":
        form = AdvertForm(request.POST)

        if(form.is_valid()):
            print(request.POST['title'])
            message = request.POST['title']

        else:
            message = 'something wrong!'


        return render_to_response('contact/advert.html',
                {'message':message},
            context_instance=RequestContext(request))

    else:
        return render_to_response('contact/advert.html',
                {'form':AdvertForm()},
            context_instance=RequestContext(request))

forms.py (form using "ModelForm")

from django import forms
from django.forms import ModelForm
from linki.models import Advert


class AdvertForm(ModelForm):
    class Meta:
        model = Advert

TEMPLATES (form html code)

<html>
<head>

</head>
    <body>
    <h1>Leave a Suggestion Here</h1>
        {% if message %}
            {{ message }}
        {% endif %}
        <div>
            <form action="" method="post">{% csrf_token %}
                {{ form.as_p }}
                <input type="submit" value="Submit Feedback" />
            </form>
        </div>
    </body>
</html>
like image 692
webfanks Avatar asked Jul 25 '12 10:07

webfanks


People also ask

How do I stop a form from refreshing after submitting?

Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.

How do I stop a page from reloading after AJAX success?

Adding type="button" attribute to button solved my problem.


3 Answers

if you are planning to use an ajax submit with jquery you should not return html from your view.. I propose you to do this instead:

html:

<html>
<head>
</head>
<body>
    <h1>Leave a Suggestion Here</h1>
        <div class="message"></div>
        <div>
            <form action="" method="post">{% csrf_token %}
                {{ form.as_p }}
                <input type="submit" value="Submit Feedback" />
            </form>
        </div>
</body>
</html>

the js

$('#form').submit(function(e){
    $.post('/url/', $(this).serialize(), function(data){ ... 
       $('.message').html(data.message);
       // of course you can do something more fancy with your respone
    });
    e.preventDefault();
});

the views.py

import json
from django.shortcuts import *
from django.template import RequestContext
from linki.forms import *

def advert(request):
    if request.method == "POST":
        form = AdvertForm(request.POST)

        message = 'something wrong!'
        if(form.is_valid()):
            print(request.POST['title'])
            message = request.POST['title']

        return HttpResponse(json.dumps({'message': message}))

    return render_to_response('contact/advert.html',
            {'form':AdvertForm()}, RequestContext(request))

so that way you put the response in the message div. instead of returning plain html you should return json.

like image 81
pahko Avatar answered Sep 29 '22 00:09

pahko


<script type="text/javascript">
$(document).ready(function() {
    $('#form_id').submit(function() { // On form submit event
        $.ajax({ // create an AJAX call...
            data: $(this).serialize(), // get the form data
            type: $(this).attr('method'), // GET or POST
            url: $(this).attr('action'), // the file to call
            success: function(response) { // on success..
                $('#success_div').html(response); // update the DIV
            },
            error: function(e, x, r) { // on error..
                $('#error_div').html(e); // update the DIV
            }
        });
        return false;
    });
});
</script>
like image 23
Jubin Thomas Avatar answered Sep 29 '22 00:09

Jubin Thomas


$('#form-id').submit(function(e){
    $.post('your/url', $(this).serialize(), function(e){ ... });
    e.preventDefault();
});
like image 25
Alexander Larikov Avatar answered Sep 28 '22 22:09

Alexander Larikov