Добавив внешний интерфейс JQuery в свое приложение для планирования мероприятий, я смог добавить возможность добавлять информацию в свое веб-приложение без обновления страницы моего сайта с помощью AJAX (асинхронный JavaScript и XML).

Первым шагом к созданию моего Ajax-ответа было прекращение естественного функционирования моей формы.

Я получаю from, выбирая его по идентификатору с помощью jquery, а затем используя функцию «preventDefault()», чтобы остановить действие формы по умолчанию

//GRAB THE SUBMIT FORM BY ID
$("#new_expense").on('submit',function(e){
//Prevent page from reloading by preventing default action
    e.preventDefault();
})

Следующим шагом было получение информации, необходимой для продолжения публикации, и добавления расходов в DOM (объектная модель документа) без необходимости обновления страницы.

$("#new_expense").on('submit',function(e){
   //THE url uses this.action which is the natural POST url for the       new expense dorm
   url = this.action
//Grabs input from form and create a text string
   data = $(this).serialize()
   
   e.preventDefault();
})

Теперь, когда у нас есть URL-адрес публикации и данные формы, пришло время опубликовать эту форму через AJAX.

$("#new_expense").on('submit',function(e){
  url = this.action
  data = $(this).serialize()
        
  $.ajax({
     // Type is a post because we are submitting a form
     type:"POST",
     // We provide the data and url which we declared above
     url: url,
     data: data,
    //once our post is successfully we use the data which is 
    //provided which will be JSON because I set my for create 
    //to redirected to a JSON view of the newly created expense.

    success: function(response) {
       // I Then used a javascript class constructor to create new 
       //expense object.
       let expense = new Expense(response)
       //Then I added the info to my table using the JQuery selector    
       //and appended it. The formatExpenseData() funtion I use just 
       //formats my data to be inserted to the table             
       $("#expense_table").append(expense.formatExpenseData())
      }
   })
  e.preventDefault();
 })

В конце концов, это блок кода, который обрабатывает это одно событие AJAX создания расходов.

$("#new_expense").on('submit',function(e){
  url = this.action
  data = $(this).serialize()
    $.ajax({
       type:"POST",
       url: url,
       data: data,
        success: function(response) {
         let expense = new Expense(response)
         $("#expense_table").append(expense.formatExpenseData())

         }
       })
  e.preventDefault();
  })
//Function TO add two decimal point to amount
function turnToDollar(amount){
      return(
        parseInt(amount).toFixed(2)
      )
}
// Expense constructor
    class Expense{
      constructor(obj) {
        this.name = obj.name
        this.quantity = obj.quantity,
        this.cost = obj.cost,
        this.id = obj.id
        this.user_id = obj.event.user_id,
        this.event_id = obj.event.id
      }
      
//Expense Prototype for format info to add to DOM
   formatExpenseData(){
     return(`
      <tr>
        <td> ${this.name} </td>
        <td>$${turnToDollar(this.cost)}</td>
        <td> ${this.quantity} </td>
        <td>$${turnToDollar(this.cost * this.quantity)}</td>
           <td<ahref="/users/${this.user_id}/events/${this.event_id}/expenses/${this.id}/edit\">Edit</a></td>
<td>
<a  data-method="delete", href="/users/${this.user_id}/events/${this.event_id}/expenses/${this.id}">Delete</a>
</td>
     </tr>
     `)
    }
 }