0

I have a problem with ajax form submission. My problem is whenever I click submi it redirect me to a new page and show me the responses there.

here is my django view

@csrf_exempt
def my_view(request):
    if request.is_ajax and request.method == "POST":
        # do something and if successfully
        return JsonResponse({'success': True}, status=200)

        # if not success
        return JsonResponse({'fail': True}, status=400)

    # other thingss

my template

<div id="form-div">
    <form action="{% url 'my_view' %}" method="POST" id="my-form">
        # some fields ..
        <button type="submit">submit</button>
    </form>
</div>

ajax

$("#my-form").submit(function (e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: my_url,
        data: {some datas},
        success: function (response) {
            # some jquery code to update DOM
        },
        error: function (response) {
            # some jquery code to update DOM
        }
    })
})

Now the code above that i showed you works fine for me but the problem comes if I append the form on event like this.

<button id="my-btn">my btn</button>

$("#my-btn).click(function(e) {
    e.preventDefault();
    
    $(#form-div).append(
    "
    <form action="{% url 'my_view' %}" method="POST" id="my-form">
        # some fields ..
        <button type="submit">submit</button>
    </form>
    "
    );
})

after I clicked the button and inspected the form it showed the exact same as my original form but if i do the post request it will redirect me the other page rather than execute the query code I defined.

What is the problem here?

ggzz
  • 27
  • 1
  • 5
  • yes it has and i can execute the event – ggzz Jan 25 '21 at 09:33
  • You need to use a delegated event handler as you're dynamically appending the new form - see the duplicate for details. Also note that it's better semantically to hook to the `submit` event of the `form` instead of the `click` of the `button` – Rory McCrossan Jan 25 '21 at 09:34

0 Answers0