简体   繁体   中英

Ajaxified form doesn't redirect

Here i am with another question :)

In my project i have a template with a form:

{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
    // wait for the DOM to be loaded
    $(document).ready(function() {
        // bind 'myForm' and provide a simple callback function
        $('#productEditForm').ajaxForm(function() {
            alert("Product with id {{ id }} saved.");
        });
    });
</script>

<h1>You're editing Product with ID={{ id }}</h1>
<form enctype="multipart/form-data" method="POST" action="/product_edit/{{ id }}" id="productEditForm">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>

The deal is that it works fine both with or without script implenmenting ajaxForm - instance of an object is being saved. But when form is "ajaxified" redirect doesn't happen though it should. I know about JQuery function preventDefault - guess in this case i need something working in reverse.

Could you please provide some help?

To redirect after the ajax request returns, you need to use a javascript function to change the location property of the window or document .

Something like:

{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
    // wait for the DOM to be loaded
    $(document).ready(function() {
        // bind 'myForm' and provide a simple callback function
        $('#productEditForm').ajaxForm(function() {
            alert("Product with id {{ id }} saved.");
            window.location.assign("/product_view/{{ id }}");
        });
    });
</script>

<h1>You're editing Product with ID={{ id }}</h1>
<form enctype="multipart/form-data" method="POST" action="/product_edit/{{ id }}" id="productEditForm">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>

This should redirect to '/product_view/{{ id }}/' on successful receipt of the ajax response back from the server after the form has been submitted. You could pass the new page as a parameter in the ajax response if you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM