django: reading from database after form submission

117 views Asked by At

I have a form in django template that call a javascript function when it's submitted:

<input name="button2" type="submit" class="test" id="button2" value="submit"
       onclick="checkSubmitStatus();"/>

After form submission, some code in python views, write the data in this form to database. like:

if request.method == 'POST':
    customer_data = Customers(CustomerID=1, CustomerName=request.POST['textfield1'])
    customer_data.save()
    return HttpResponse(status=204)

And in the javascript function I have used ajax to get some data from server:

<script type="text/javascript">
    function checkSubmitStatus() {
        $.ajax({
            url: "CustomerData",
            type: 'get',
            datatype: 'html',
            async: false,
            success: function(data) {
                x = data;
            }
        });
            Alert(x);
    }

when CustomerData reads the data from DB:

return HttpResponse(Customers.objects.get(CustomerID=1).CustomerName)

I expect the CustomerData to deliver modified data (the data I enter in the template form), while it returns the previous data. When I refresh the page I can see the updated data. So I'm sure the form data is written to DB, but the script shows shabby data.

1

There are 1 answers

3
Daniel Roseman On

This code doesn't make much sense. Your JS function is called on submit; that is, at the point where the submit button is clicked. But at that point, the data does not exist yet, because you haven't submitted the form; and in any case, any Ajax call is going to be immediately replaced by the submission action anyway, so the callback is never going to be invoked.

I don't understand why you have this mixed form POST / Ajax GET. Either submit the form via Ajax and return the updated data in that call; or, submit the form normally, and return the updated data in the standard HTML response from the submission.