1

I have become very swamped by my django website since I have started using jquery and ajax. I am new to ajax and javascript so please keep that in mind when responding and sorry if I am a bit confused.

Basically I have a template that has a form to create a recipe. I use jquery .load to load this template to a popup div on another page. The form seems to load into the div fine but when I try and submit the form, nothing happens (no validation check or anything - if i leave fields empty it returns no error.) The strange thing is that when i visit the actual page I am loading with jquery, the form works perfectly. This has been bogging me down quite a bit and I would love to move on so any help is much appreciated.

here is the load script:

<script type="text/javascript">
$(document).ready(function(){
    $(".create").on("click", function(){
        $("#popupContact").load("/cookbook/createrecipe #createform");
    });
});
</script>

template for page loading the form:

{% block content %}
{% autopaginate recipe_list 6 %}
    <div id="recipe_cont">
            {% for recipe in recipe_list %}
        <div class="recipe">
            <div class="button">    
            <a href="{% url cookbook.views.userrecipe recipe.id %}" style="display: none;"></a>
            <h4>{{ recipe.name }}</h4>
            <h5>{{ recipe.author }}</h5>
            <h5>Prep Time: {{ recipe.prep_time }} minutes</h5>
            </div>
        </div>
    {% endfor %}
    </div>
    <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>
{% endblock %}

create-recipe template:

{% extends "cookbook/base.html" %}
    {% block content %}
    <div id="createform">
    <h1>Create New Recipe</h1>
        <form action="." method="POST">
            <table>
                {% csrf_token %}
                {{ form.as_table }}
            </table>
            <p><input type="submit" value="Submit"></p>
        </form>
    </div>
    {% endblock %}

create-recipe 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))

javascript code for jquery-form:

<script> 
    // wait for the DOM to be loaded 
    $(document).ready(function() { 
        var options ={
            target: '#popupContact',
            url: '{% url createrecipe %}',
            success: function() { 
            alert("Thank you for your comment!"); 
        }
    };
        $('#createrecipe').ajaxForm(options); 
    }); 
</script> 

thanks, snackerfish

edit1: mark has pointed out that my form action was wrong and so that was resolved.

1 Answer 1

1

The form action for the create form is the current page '.'. If you load this on the create page url that will work fine as you noted. However if you load this on the listing page with a popup then it will submit the form to the list view which is not correct. Setting the action="{% url 'create-view' %}" will correct this issue. 'create-view' would be replaced with the name for the create view pattern.

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

7 Comments

for some reason when i change the . to {% url 'createrecipe' %} the form no longer loads into the div. but i think this is the correct answer, any idea why it won't load anymore?
the syntax to quote the url name assumes you are using {% load url from future %} for future compatibility. If not you should removed the quotes.
i have one more question - when i hit submit while there are errors on the it redirects to the actual createrecipe page to display errors. is there anyway to have it redirect to stay in the popup div on the page it was loaded on? thanks mark
Yes it's possible but you'll need to make the submit over AJAX and handle both AJAX and non-AJAX POSTs in the view. I would recommend looking at jquery-form jquery.malsup.com/form.
jquery-form is just what i have been looking for although i am missing a few pieces. do you think you can check out my code and tell me what i am missing - i have updated my post thanks mark
|

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.