Home > database >  Issue with nested Ajax calls
Issue with nested Ajax calls

Time:02-15

I am having a series of nested Ajax calls to create and update data into the database as well as calling the updated list once data are successfully submitted.

This is how the code works:

(1) A list of transaction is shown when the page is rendered, each row can be edited by the user.

(2) When clicking a specific row, I run an Ajax call to retrive the form filled with the data to be updated

(3) The form is then submitted via Ajax as well.

(4) If successfully submitted it perform another Ajax call to get the table updated.

First problem: when the table is loaded via Ajax the "edit" button is not working anymore. Second problem: The form displayed to update and to create is the same, except when updating the form is pre-filled. I would like to avoid duplicating the Ajax call but I had to do it otherwise I wasn't able to submit the form after it was loaded from the first Ajax call (pt 1). Is there a way to make a more clean code?

Here it is the javascript code, server side all works just fine:

$(".edit-transaction").click(function () {
  // obtain the object id to load the correct form
  const object_id = $(this).data('object-id');

  // request the form via AJAX Get request
  $.ajax({
    type: 'GET',
    url: "/transaction/",
    data: {
      'slug': object_id
    },
    success: function(response) {
      // Get the form for the requested object
      $("#display-form").html(response.html); // this code retrive the form
      $("#transaction-form").submit(function (e) { 
        // preventing from page reload and default actions
        e.preventDefault();

        let serializedData = $(this).serialize();

        // Update the form via AJAX
        $.ajax({
          type: 'POST',
          url: "/transaction/",
          data: serializedData,
          success: function (response) {
            console.log('updated successfully')

            // load the table with the new content updated
            $.ajax({
              type: 'GET',
              url: "/get-transactions-list/",
              success: function (data) {
                $("#display-transaction-list").html(data.html);
              },
            });
          },
          error: function (response) {
            let error = response ["responseJSON"]["error"];
            $.each(error, function (code, message) {
              alert('message');
            });
          }
        })
      })
    },
    error: function (response) {
      let error = response ["responseJSON"]["error"];
      $.each(error, function (code, message) {
        alert('message');
      });
    }
  })

});
$("#transaction-form").submit(function (e) {
  // preventing from page reload and default actions
  e.preventDefault();
  let serializedData = $(this).serialize();

  // Create a new transaction via AJAX
  $.ajax({
    type: 'POST',
    url: "/transaction/",
    data: serializedData,
    success: function (response) {
      console.log('created successfully')
      // load the table with the new content updated
      $.ajax({
        type: 'GET',
        url: "/get-transactions-list/",
        success: function (data) {
          $("#display-transaction-list").html(data.html);
        },
      });
    },
    error: function (response) {
      let error = response ["responseJSON"]["error"];
      $.each(error, function (code, message) {
        alert('message');
      });
    }
  })
})

Thanks for any help

CodePudding user response:

Since some of the elements are added asynchronously, this means that the event listeners which were added at runtime will not affect those elements. You should instead listen to events on them via "events delegation".

You can also create a custom event for loading the table content. So to update the table, you just .trigger() your custom event. This is useful when you want to implement other functionalities which will need a table update like, delete, etc.

// custom event for loading the table content
$(document).on('load.table', '#display-transaction-list', function () {
    const $table = $(this);
    $.ajax({
        type: 'GET',
        url: "/get-transactions-list/",
        success: (data) => $table.html(data.html)
    });
});
// edit transaction event
$(document).on('click', '.edit-transaction', function () {
    // obtain the object id to load the correct form
    const object_id = $(this).data('object-id');

    // request the form via AJAX Get request
    $.ajax({
            type: 'GET',
            url: "/transaction/",
            data: {
                'slug': object_id
            },
            success: function(response) {
                // Get the form for the requested object
                $("#display-form").html(response.html); // this code retrive the form
            },
            error: function (response) {
                let error = response ["responseJSON"]["error"];
                $.each(error, function (code, message) {
                alert('message');
            });
        }
    })
});
// save transaction event
$(document).on('submit', '#transaction-form', function (e) { 
    // preventing from page reload and default actions
    e.preventDefault();

    let serializedData = $(this).serialize();

    // Update the form via AJAX
    $.ajax({
        type: 'POST',
        url: "/transaction/",
        data: serializedData,
        success: function (response) {
            // you can add some data to the response 
            // to differentiate between created and updated. Eg response.actionType
            console.log('created or updated successfully')

            // load the table with the new content updated
            $("#display-transaction-list").trigger('load.table');
        },
        error: function (response) {
            let error = response ["responseJSON"]["error"];
            $.each(error, function (code, message) {
                alert('message');
            });
        }
    })
})

  • Related