0

I have a form and want to send data to server via AJAX:

$('#edit_form').submit(function () {
            var url = "/edit/";
            /*$("#edit_form :input").prop("disabled", true);*/
            $.post(url, $(this).serialize())
                .done(function (data) {
                    $('body').html(data);
            });
        });

My view:

def edit_main_page(request):
    try:
        person = Person.objects.first()
    except ObjectDoesNotExist:
        person = None
    if request.method == 'POST':
        form = MainPageForm(request.POST, instance=person)
        if form.is_valid():
            args={}
            args['person']=form.save()
            if request.is_ajax():
                html = render_to_string('index_ajax.html', args)
                return HttpResponse(html)
            else:
                return redirect(reverse('home'))
    else:
        form = MainPageForm(instance=person)
    return render(request, 'edit.html', {'form': form})

When debuging, firs time I submit form then request.is_ajax() returns False, then I back to that page and submit again it can be True. Debuging my script, I see that ajax request is executed. While debuggin, when I submit form several times, request.is_ajax() can be 4 times False and one time True

Cœur
  • 37,241
  • 25
  • 195
  • 267
litwisha
  • 392
  • 3
  • 12
  • Definitely not making [a cross-domain request?](http://stackoverflow.com/a/7757509/267781) – MattH Jul 24 '15 at 20:33
  • MattH, it doesn't work. For example, if I debug Django code and script at the same time, then first submition is not ajax. and the second is ajax. And in when running, if click save it throws `error: [Errno 32] Broken pipe` but server is still running – litwisha Jul 24 '15 at 21:16
  • 1
    Couple of things: You need to prevent the default form submit using `e.preventDefault()` and also, if this form is being rendered dynamically, use `.on` for event delegation – karthikr Jul 27 '15 at 03:08

0 Answers0