reset form when div is closed using ajax

how can i reset my form to its original state when i close a div

i am using ajax and django

one recommendation was to use a reset_recipe field in my form that if set to true will reset the recipe

here is my disablePopup function:

function disablePopup($contact_selector){
//disables popup only if it is enabled
if(popupStatus==1){
    $("#backgroundPopup").fadeOut("fast");
    $contact_selector.fadeOut("fast");
    popupStatus = 0;
    var form = $("form#createrecipeform");
    console.log(form);
    form.submit(function(e) {
    e.preventDefault();
    console.log('ajax form submission function called successfully.');
    form = $(this);
    console.log(form);
    var serialized_form = form.serialize();
        $.ajax({ type: "POST", 
            url: $(this).attr('action'),
            data: serialized_form, 
            success: (function(data) { 
                console.log('ajax success function called successfully.');
                data = $.parseJSON(data);
                if (data.success) {
                    console.log('success');
                    var newForm = data.form;
                    form.replaceWith(newForm);
                } else {
                    console.log('failure');
                    var newForm = data.form;
                    form.replaceWith(newForm);  
                }
            })
        });
        return false;
    });

}

}

here is the view that i create my recipe with

def createrecipe(request):
        print "entering createrecipeview"
        if request.method == 'POST':
            print "form is a post"
            form = RecipeForm(request.POST)
            if form.is_valid():
                print "form is valid"
                form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})
                form = form.save()
                if form.cleaned_data['reset_recipe'] == "True"://here is the line that uses the reset_recipe function but right ow it is not working 
                    print "reset recipe"
                    form = RecipeForm(initial = {"original_cookbook": request.user.cookbooks.all()[0]})
                    t = loader.get_template('cookbook/create_form.html')
                    c = RequestContext(request, {
                    'form': form,
                    })

                    data = {
                    'replace': True,
                    'form': t.render(c),
                    'success': False,
                    }

                    json = simplejson.dumps(data)
                    return HttpResponse(json,mimetype='text/plain')
                t = loader.get_template('cookbook/create_form.html')
                c = RequestContext(request, {
                'form': form,
                })

                data = {
                'replace': True,
                'form': t.render(c),
                'success': True,
                }

                json = simplejson.dumps(data)
                return HttpResponse(json, mimetype='text/plain')
            else:
                print "form is invalid"
                form = RecipeForm(request.POST)
                t = loader.get_template('cookbook/create_form.html')
                c = RequestContext(request, {
                    'form':form,
                })

                data ={
                    'form': t.render(c),
                    'success': False,
                }

                json = simplejson.dumps(data)
                return HttpResponse(json, mimetype='text/plain')

right now when i try to close the div it redirects to a page and gives me the following code:

{"success": false, "form": "<form action=\"/cookbook/createrecipe/\" method=\"POST\" id=\"createrecipeform\">\n\t<table>\n\t\t<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='3fb6b9952f50edbe7654666ef20a6900' /></div>\n\t\t<tr><th><label for=\"id_name\">Name:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input id=\"id_name\" type=\"text\" name=\"name\" maxlength=\"200\" /></td></tr>\n<tr><th><label for=\"id_author\">Author:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input id=\"id_author\" type=\"text\" name=\"author\" maxlength=\"100\" /></td></tr>\n<tr><th><label for=\"id_picture\">Picture:</label></th><td><input type=\"file\" name=\"picture\" id=\"id_picture\" /></td></tr>\n<tr><th><label for=\"id_ingredients\">Ingredients:</label></th><td><ul class=\"errorlist\"><li>This field cannot be null.</li></ul><textarea id=\"id_ingredients\" rows=\"10\" cols=\"40\" name=\"ingredients\"></textarea></td></tr>\n<tr><th><label for=\"id_steps\">Steps:</label></th><td><ul class=\"errorlist\"><li>This field cannot be null.</li></ul><textarea id=\"id_steps\" rows=\"10\" cols=\"40\" name=\"steps\"></textarea></td></tr>\n<tr><th><label for=\"id_prep_time\">Prep time:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input type=\"text\" name=\"prep_time\" id=\"id_prep_time\" /></td></tr>\n<tr><th><label for=\"id_type\">Type:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><select name=\"type\" id=\"id_type\">\n<option value=\"\" selected=\"selected\">---------</option>\n<option value=\"SW\">Sandwich</option>\n<option value=\"AP\">Appetizers</option>\n<option value=\"SD\">Sauces and Dressings</option>\n<option value=\"SS\">Soups and Salads</option>\n<option value=\"VG\">Vegetables</option>\n<option value=\"RG\">Rice, Grains and Beans</option>\n<option value=\"PA\">Pasta</option>\n<option value=\"BR\">Breakfast</option>\n<option value=\"MT\">Meat</option>\n<option value=\"SF\">Seafood</option>\n<option value=\"BP\">Bread and Pizza</option>\n<option value=\"DT\">Desserts</option>\n</select><input type=\"hidden\" name=\"reset_recipe\" value=\"False\" id=\"id_reset_recipe\" /></td></tr>\n\t</table>\n\t<p><input type=\"submit\" value=\"Submit\"></p>\n</form>"}

another thing to note is that the page redirects to the form action page

sorry for so much code but it all seems relevant

thanks

katie

Answers


$("#createrecipeform").attr('reset_recipe', "True");

Will only add an attribute to the form element:

<form reset_recipe="True" id="createrecipeform">

You need to add an input element to the form called reset_recipe.

Add a hidden field to your form:

reset_recipe = forms.CharField(widget=django.forms.widgets.HiddenInput, required=False)

And the set its value to True (instead of adding an attribute to the form):

$("#id_reset_recipe").val("True");

It also looks like you are just submitting your form (without AJAX):

$("#createrecipeform").submit();

You need to submit it via XHR:

$("#createrecipeform").submit(function(event){
    /* stop form from submitting normally */
    event.preventDefault(); 

    /* get form field values */
    var serialized_data = $( this ).serialize();

    /* Send the data using post and put the results in the form */
    $.post( url, serialized_data,
      function( data ) {
          $("#createrecipeform").replace( data.form );
      }
    );
 });

Also use the correct mime type for json:

return HttpResponse(json, mimetype='application/json')

But if you just want to reset the form you can usually just use:

$("#createrecipeform").reset()

Need Your Help

Merging two files with awk and changing last column for duplicates

file join awk merge

I have two tab-delimited text files. I want to create an output file that has all the lines in file 1. However if the value in column 1 in file 1 matches column 1 in file 2, I would like the value in

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.