0

I have a basic page where an user can perform an action using a standard form. Since i need my page not to reload when the form is submitted, instead of using Django Forms to handle submitting, i'm using Ajax.

When the form is submitting, an Ajax request is fired to my Django view, which at the moment should just print out the content of the request, in order to let me debug it.

Everything is working, but now i want to add an option for the user to buy more items at the same time, since it's an ecommerce site. So i need a way to submit the same form multiple times with different data and with a single button.

Here is the ajax function i use to send the request:

$(document).ready(function () {

  $("#myform").submit(function (event) {
      callAJAX( "/myview/",
       {"X-CSRFToken": getCookie("csrftoken") },
       parameters={
      'item': $('#item').val(), 'amount': $('#amount').val()},

      'post',
       function(data){
        console.log('Request fired.')

       }, null, null );
  return false; 
  });
});

This will work:, the following form will send a standard request to my Django view containing the item and the amount chosen by the user.

<form method='post' id='myform'>
  {% csrf_token %}
  <input type="text" placeholder="Item" id='item'>
  <input type="text" placeholder="Amount" id='amount'>
  <button name="button1" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form>

But what if i want to submit two forms in the same page?

I tried this:

<form method='post' id='myform'>
  {% csrf_token %}
  <input type="text" placeholder="Item" id='item'>
  <input type="text" placeholder="Amount" id='amount'>
</form>

<form method='post' id='myform'>
  {% csrf_token %}
  <input type="text" placeholder="Item" id='item'>
  <input type="text" placeholder="Amount" id='amount'>
</form>
<button name="button1" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>

This is not going to work, because the button is not in the same field as any of the two forms, but the desired output is to submit the following two forms at the same time, sending two different requests, one for each form.

So, what should happen is: say the input is Amount one and Item one for the first form, and Amount two and Item two for the second form, those values should be sent at the same time as two different request to my Django view, so that i can have something like this when debugging:

REQUEST: 'Amount one', 'Item one'
REQUEST: 'Amount two', 'Item two'

Is it even possible to do? Or should i just create more forms and more Ajax functions, one for each form? Any advice is appreciated

8
  • This doesn't make sense, you can't submit multiple forms at the same time. If you look at all e-commerce sites nowadays, they have a cart and users add items to the shopping cart one at a time. So you still only submit one item via ajax, and your view adds it to the user's shopping cart. It doesn't make sense to submit multiple items at once and that's not even what users are expecting. Commented Feb 3, 2020 at 18:08
  • I know it might not make sense at first, but it's just part of a feature i want to add. I'm not making a cart, i just want to know how to submit two forms using a single button and send two request, each for every form, so that my django view can receive the data and save it, it's just that Commented Feb 3, 2020 at 18:20
  • If you send two HTTP requests, you're also triggering your view twice. So each time your view is triggered, it needs to add the items received somewhere (that's what we usually call a cart). Even if you don't show the actual cart, you'll still have to keep the state of the cart somewhere so you know what the user ordered. Commented Feb 3, 2020 at 18:46
  • You can also wrap everything in one form instead of using two forms. Then your submit button works. But you'll have to uniquely name all your fields so that they can be distinguished from each other. A way to do that is to use a model formset. In your HTML you have one form (and your javascript can just submit the form's data), but in your view you handle a formset which is essentially multiple forms for the same model. Commented Feb 3, 2020 at 18:49
  • Note that in that case you should use Django's form rendering tools to ensure the input fields have the correct names and ids. Your HTML should never contain duplicated ids, e.g. your HTML shown above is wrong. Commented Feb 3, 2020 at 18:55

1 Answer 1

1

Just change your jQuery trigger from submit() on the form to click() on the button. Then send 2 AJAX requests in your click().

    $("#my_button").click(function (event) {
      event.preventDefault(); // prevent form from being submitted automatically
      callAJAX( "/myview/",
       {"X-CSRFToken": getCookie("csrftoken") },
       parameters={
       'item': $('#item1').val(), 'amount': $('#amount1').val()},

       'post',
       function(data){
        console.log('Request fired.')

       }, null, null );

      // Call ajax again with other items and amounts
      callAJAX( "/myview/",
       {"X-CSRFToken": getCookie("csrftoken") },
       parameters={
       'item': $('#item2').val(), 'amount': $('#amount2').val()},

       'post',
       function(data){
        console.log('Request fired.')

       }, null, null );
    });
    <form method='post' id='myform'>
      {% csrf_token %}
      <input type="text" placeholder="Item" id='item1'>
      <input type="text" placeholder="Amount" id='amount1'>
    </form>

    <form method='post' id='myform'>
      {% csrf_token %}
      <input type="text" placeholder="Item" id='item2'>
      <input type="text" placeholder="Amount" id='amount2'>
    </form>
    <button name="button1" id="my_button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>

Note that I gave the button an id and changed the ids of the items and amounts to avoid duplicate ids.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.