0

I want to edit table( with input which locate in it cells) sendind Ajax on backend with JQuery. After this my table must refresh.

This my code:

editTable.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>

<table>
    <thead>
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>LastName</th>
        <th>Phone</th>
        <th>Email</th>
    </tr>
    </thead>

    <tbody>
    <tr th:if="${records.empty}">
        <td colspan="5"> No Records Available </td>
    </tr>
    <tr th:fragment="entity-row" th:each="record : ${records}">
        <form id="subscription_order_form"  th:action="@{/changeElementTable}" method="post">
       <td><input th:value="${record.id}" name="id"  ></td>
            <td><input th:value="${record.firstName}"  id="firstName" name="firstName" ></td>
            <td><input th:value="${record.lastName}" id="lastName" name="lastName"  ></td>
            <td><input th:value="${record.phoneNumber}" id="phoneNumber" name="phoneNumber"  ></td>
            <td><input th:value="${record.email}" id="email" name="email"  ></td>
            <td><input th:value="${record.id}"  id="idRepeat" type="hidden" name="idRepeat" ></td>
            <td><button  id="button" onclick="editAjax()"  >Отправить</button></td>
        </form>
    </tr>
    <tr></tr>
    <th></th>
    </tbody>

</table>

<script>
function editAjax() {
$(':input').removeAttr('readonly');
var form_data = new FormData();
 form_data.append('id', $("#id").val());
 form_data.append('firstName', $("#firstName").val());
 form_data.append('lastName', $("#lastName").val());
 form_data.append('phoneNumber', $("#phoneNumber").val());
 form_data.append('email', $("#email").val());
 form_data.append('idRepeat', $("#idRepeat").val());

$.ajax({
    url : '/changeElementTable',
    type: 'POST',
    data:form_data,
    success : function(responce) {



    },
    error : function(){
        alert("error");
    }
});
}


</script>

</body>
</html>

Code of Controller Java/Spring:

package ru.noorsoft.javaeducation;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Entity;
import java.util.List;

@Controller
public class TableController {
    private TableRepository tableRepository;

    public TableController(TableRepository tableRepository)
    {
        this.tableRepository=tableRepository;
    }

    @GetMapping("/editTableController")
    public String showEdit(
            Model model) {

        model.addAttribute("records", tableRepository.findAll());

        return "editTable";
    }

    @PostMapping("/changeElementTable")
    public String editRecordTable(@RequestParam(name="id")String idFirst,
            @RequestParam(name="firstName")String firstName,
                                 @RequestParam(name="lastName")String lastName,
                                 @RequestParam(name="phoneNumber")String phoneNumber,
                                 @RequestParam(name="email")String email,
                                  @RequestParam(name="idRepeat")String idHidden,
                                 Model model) {
        Long idF=Long.parseLong(idFirst);
        Long idH=Long.parseLong(idHidden);
         tableRepository.findById(idH).get().setId(idF);
        tableRepository.findById(idH).get().setFirstName(firstName);
        tableRepository.findById(idH).get().setLastName(lastName);
        tableRepository.findById(idH).get().setPhoneNumber(phoneNumber);
        tableRepository.findById(idH).get().setEmail(email);
        tableRepository.save( tableRepository.findById(idH).get());
        model.addAttribute("records", tableRepository.findAll());

        return  "editTable";
    }

}

But when i click the button ajax do not send, send request (without ajax) on backend. Please help me resolve this problem.

  • You're trying to send your 'form_data' object to the controller, however you're fetching all the parameters as an individual string. either catch these parameters through url individually or create a new java class to catch your 'form_data' object as a request-body. Also, for Ajax call the controller has to have the '@ResponseBody' annotation. – Sumit Jul 09 '20 at 07:54

2 Answers2

0

Try to use this code on editTable.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>

<table>
    <thead>
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>LastName</th>
        <th>Phone</th>
        <th>Email</th>
    </tr>
    </thead>

    <tbody>
    <tr th:if="${records.empty}">
        <td colspan="5"> No Records Available </td>
    </tr>
    <tr th:fragment="entity-row" th:each="record : ${records}">
    <form id="subscription_order_form"  th:action="@{/changeElementTable}" method="post">
       <td><input th:value="${record.id}" name="id"  ></td>
            <td><input th:value="${record.firstName}"  id="firstName" name="firstName" ></td>
            <td><input th:value="${record.lastName}" id="lastName" name="lastName"  ></td>
            <td><input th:value="${record.phoneNumber}" id="phoneNumber" name="phoneNumber"  ></td>
            <td><input th:value="${record.email}" id="email" name="email"  ></td>
            <td><input th:value="${record.id}"  id="idRepeat" type="hidden" name="idRepeat" ></td>
            <td><button id="button">Отправить</button></td>
        </form>
    </tr>
    <tr></tr>
    <th></th>
    </tbody>

</table>

<script>
$("#subscription_order_form").submit(function(e) {
    e.preventDefault();
    editAjax();
})
function editAjax() {
    $(':input').removeAttr('readonly');
    var form_data = $('#subscription_order_form').serialize();

    $.ajax({
        url : '/changeElementTable',
        type: 'POST',
        data:form_data,
        success : function(responce) {



        },
        error : function(){
            alert("error");
        }
    });
}
</script>
myscode
  • 75
  • 1
  • 3
0

Setting processData to false will prevent jQuery transforming the data into a query string. See the docs for more info.

Setting the contentType to false is imperative, since otherwise jQuery will set it incorrectly.

Read more discussion here

$.ajax({
   url : '/changeElementTable',
   type: 'POST',
   data: form_data,
   contentType: false,
   processData: false,
   success : function(responce) {
   },
   error : function(){
     alert("error");
   }
});
HVD
  • 231
  • 1
  • 13