Django ajax post form

Django -- Posted on Nov. 20, 2021

The code you provided is a JavaScript/jQuery script that handles form submission and AJAX requests. It seems to be a client-side script that interacts with a server to handle form data submission and processing.

Here's a breakdown of what the code does:

  1. $('body').on('submit', 'form', function(e){ ... }): This line attaches an event handler to the 'submit' event of any form element on the page. When a form is submitted, the following function will be executed.

  2. e.preventDefault();: This line prevents the default form submission behavior, which would cause a page reload.

  3. $('input, select').removeClass('is-invalid');: This line removes the 'is-invalid' class from all input and select elements on the page. This class is commonly used to highlight invalid form fields with CSS.

  4. $( ".invalid-feedback" ).remove();: This line removes any existing elements with the class 'invalid-feedback', which might have been previously appended to show error messages.

  5. var $form = $(this);: This line stores the form element that triggered the submit event in the variable '$form' for later use.

  6. var data = $form.serialize();: This line serializes the form data into a query string format, which will be sent in the AJAX request to the server.

  7. var url_link = $form.attr('action');: This line retrieves the 'action' attribute of the form, which is the URL where the form data will be submitted.

  8. $.when($.ajax({ ... })).then(function( response, textStatus, jqXHR ) { ... }): This line initiates an AJAX request to the server using jQuery's $.ajax() function. It wraps the AJAX call inside a $.when().then() construct, which allows handling success and failure cases more conveniently.

  9. If the AJAX request is successful, the then() function executes, and the server's response is stored in the 'response' variable. The response is expected to be in JSON format.

  10. var obj = JSON.parse(response);: This line parses the JSON response into a JavaScript object and stores it in the 'obj' variable.

  11. $('form')[0].reset();: This line resets the form, clearing all input fields and selecting the first form element on the page. The assumption here is that there's only one form on the page.

  12. var app = obj[0].model.split('.')[0];: This line extracts the 'app' part from the 'model' field in the first object of the 'obj' array. The 'model' field appears to contain a string with two parts separated by a dot (e.g., 'app.model'). This code splits that string and stores the first part in the 'app' variable.

  13. var model = obj[0].model.split('.')[1];: This line extracts the 'model' part from the 'model' field in the first object of the 'obj' array and stores it in the 'model' variable.

  14. The code then logs the 'app' and 'model' variables to the console.

  15. $("[id$='"+ model + "-list']").prepend("<li>" + obj[0].fields['name'] + "</li>");: This line selects an element whose 'id' attribute ends with the value of the 'model' variable followed by "-list". It then prepends a new list item ("<li>") containing the value of the 'name' field from the 'fields' object in the first object of the 'obj' array. This is likely used to dynamically update a list with new data returned from the server.

  16. If the AJAX request fails, the catch() function executes. It expects the server to respond with JSON data containing error information. The code iterates through the error data and adds the 'is-invalid' class to the corresponding input/select elements and appends error messages after the invalid fields.

Overall, this script appears to handle form submissions, communicates with the server using AJAX to process the form data, and updates the UI based on the server's response. It also handles and displays error messages in case of form validation failures on the server-side.

 

              
                $('body').on('submit', 'form', function(e){
        e.preventDefault();
        $('input, select').removeClass('is-invalid');
        $( ".invalid-feedback" ).remove();
        var $form = $(this);
        var data = $form.serialize();
        var url_link = $form.attr('action');
        $.when($.ajax({
          url: url_link,
          data:data,
          method:  $form.attr('method'),
          datatype: 'json',
        })).then(function( response, textStatus, jqXHR ) {
        var obj = JSON.parse(response);
        console.info(obj)
        $('form')[0].reset();
        var app = obj[0].model.split('.')[0];
        var model = obj[0].model.split('.')[1];
        console.info("app:" + app);
        console.info("model:" + model);
        $("[id$='"+ model + "-list']").prepend("<li>" + obj[0].fields['name'] + "</li>");
      }).catch(function(err){
        $.each(err.responseJSON, function(index, value){
          console.info(index, value);
          $('#id_'+ index).addClass('is-invalid');
          $('#id_'+ index).after("<div class='invalid-feedback'>" + value + "</div>");
        });
      });
    })
                  
   
            

Related Posts