0

I am loading a form to a popup div using the jquery.load() function and so far it is working nicely. What i would like to add is when the form is submitted with errors it will load the error mark up form back into the popup div instead of redirecting to the actual form page, which it is currently doing.

Someone recommended that I use jquery-form which i think would work perfectly. I just don't know how to implement it.

here is the .load() function:

$(document).ready(function(){
        $(".create").on("click", function(){
            $("#popupContact").load("/cookbook/createrecipe #createform");
        });
});

here is the page that loads the form:

<div id="popupContact" class="popup">
        <a id="popupContactClose" style="cursor:pointer;float:right;">x</a>
        <p id="contactArea">
        </p>
</div>
<div id="backgroundPopup">
</div>  
<div id="col2-footer">
{% paginate %}
</div>

here is my form template:

<div id="createform">
<h1>Create New Recipe</h1>
    <form id="createrecipe" action="{% url createrecipe %}" method="POST">
        <table>
            {% csrf_token %}
            {{ form.as_table }}
        </table>
        <p><input type="submit" value="Submit"></p>
    </form>
</div>

here is my attempt to use the jquery-form:

<script> 
    // wait for the DOM to be loaded 
    $(document).ready(function() { 
        var options ={
            target: '.popup',
    };
    $('#createrecipe').submit(function() {
        $(this).ajaxSubmit(options); 
        return false;
    }); 
});
</script> 

createrecipe view:

def createrecipe(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/index/')
    else:
        if request.method == 'POST':
            print 1
            form = RecipeForm(request.POST)
            if form.is_valid():
                print 2
                recipe = form.save(commit=False)
                recipe.original_cookbook = request.user.cookbooks.all()[0]
                recipe.pub_date = datetime.datetime.now()
                recipe.save()
                user = request.user
                cookbooks = user.cookbooks
                cookbook = cookbooks.all()[0]
                cookbook.recipes.add(recipe)
                return HttpResponseRedirect('/account')
        else:
            form = RecipeForm()

        return render_to_response('cookbook/createrecipe.html',
                                    {'form':form},
                              context_instance=RequestContext(request))

thank you snackerfish

2 Answers 2

0

Because you use jquery anyway you should submit your form via ajax otherwise you will be redirected:

 $('#createform form').submit(function(e) {
 e.preventDefault();
 $.post("/your views url/", { 
            data: $('#createform form').serialize(),
            },function(data){ //this is the successfunction 
                              //data is what your view returns}
 });

Your view should return the errors as json so that you can process them inside your javascript:

from django.utils import simplejson

def ajax_recipe(request):
    if request.method == 'POST':
        form = YourForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse("ok")
        else:
            errors = form.errors
            return HttpResponse(simplejson.dumps(errors))
    else:
        data = "error"
        return HttpResponse(data)

With that markup you can place your form errors where ever you want, using the jquery post success function.

if(data == "ok"){do something}
// else error handling
var errors = jQuery.parseJSON(data)
if(errors.somefield){//place errors.somefield anywhere}

Note the code is not tested. But thats the way I would go.

Edit

Note to make this work you have to set a custom X-CSRFToken header to the value of the CSRF token on each XMLHttpRequest. in other words copy and paste the script from the django docs inside your template: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

Thats how you could raise the errors insid your Form.py

def clean_somefield(self):
        somefield = self.cleaned_data.get('some field')
        if not somefield:
            raise forms.ValidationError(u'This field is required.')
Sign up to request clarification or add additional context in comments.

5 Comments

after the function(data){ call what would i put in that function? sorry i didnt see the code at the end
jarred, I hope i was right in saying errors - what I meant is when there are missing fields on submit, the loaded page on click of the submit button will redirect me to the page that i loaded and show me the required fields instead of showing the same page in the load() div
you don't need a redirect... if the field is required the field error will be: this field is required.
ok i will give this some thought and see where it takes me thanks jarred
I don't know if that is a good solution. You could use the clean methods in your form to raise the validation errors.
0

i had an error in the syntax of my javascript all is ok

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.