Send multiple Post requests using ajax on button click in the same page

1up

Hi I am working on a jsp page, which renders multiple values dynamically and show a button on each value, when i click on each button i should trigger a ajax call which sends that value to the backend.

for example

value1 add

value2 add

when i click on add for value 1 then value 1 should be sending as part of the post request.

i cannot add id's for each element because as this page is a dynamic page. i have looked some of the stack overflow answers but they are all using ID in their element.

Please find the image if you have no idea what i am talking about Please suggest.

The jsp i wrote.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<title>Items List</title>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<h1>Welcome to LassiShop </h1>
<c:set var="url" value="/cart"/>
<c:if test="${itemsData.size() gt 0}">
  <table class="table">
    <thead>
      <tr>
        <th scope="col">Name</th>
        <th scope="col">Price</th>
        <th scope="col">Quantity</th>
      </tr>
    </thead>
    <tbody>
      <c:forEach items="${itemsData}" var="item">
      <div class="form">
        <tr>
          <td>
            <c:out value="${item.name}"/>
            <input type="hidden" class="name" value="${item.name}">
          </td>
          <td>
            <c:out value="${item.price}"/>
            <input type="hidden" class="price" value="${item.price}">
           </td>
          <td><input type="number" class="quantity"/></td>
          <td><button class="btn btn-primary" type="submit">ADD TO CART</button></td>
        </tr>
       </div>
      </c:forEach>
    </tbody>
  </table>
</c:if>
<c:if test="${itemsData.size() eq 0}">
    <h3>No Products available for this Category</h3>
</c:if>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script>
$(document).on('click',".btn",function(){
var itemData = {};
    itemData["name"] = $('.name').text();
    itemData["price"] = $('.price').text();
    itemData["quantity"] = $('.quantity').text();
    console.log(itemData);
    $.ajax({
        type : "POST",
        contentType : "application/json",
        url : "/cart",
        data : JSON.stringify(itemData),
        dataType : 'json',
        async:true
    });
});
</script>
</body>
</html>


The controller class

@RequestMapping(value = "/cart", method = RequestMethod.POST, produces = "application/json")
    public @ResponseBody String testCart(@RequestBody CartEntryData cartEntry){
        System.out.println(cartEntry.getName());
        System.out.println(cartEntry.getPrice());
        System.out.println(cartEntry.getQuantity());
        return "itemsList";
    }

Please refer to the picture above to see how my products are getting displayed.

Note here that i cannot use ID since this is dynamic,i need to somehow get the data from the front end & send it to the controller class.

The above jquery doesn't work because the syntax is either false or wrong.

charlietfl

Several issues:

  1. <div> is invalid child of <tbody> and invalid parent of <tr>.
  2. Use val() not text() to get value from form controls like <input>, <select> etc.
  3. You need the specific row instance of each of the values to send. To do that use closest() to isolate the row and find() to get the specific element within the row something like:

$(document).on('click', ".btn", function() {
  // `this` is the button event occured on
  var $row = $(this).closest('tr');
  
  var itemData = {
    name: $row.find('.name').val(),
    price: $row.find('.price').val(),
    quantity: $row.find('.quantity').val()

  };
  console.log(itemData)
  $.ajax({
    type: "POST",
    contentType: "application/json",
    url: "/cart",
    data: JSON.stringify(itemData),
    dataType: 'json',
    //async: true  pointless as this is default
  });
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to post a value to a controller function on button click using Ajax and also redirect to new page at the same time?

Stop multiple AJAX requests in same page

send multiple http requests using same socket

how to send multiple requests using same client?

How do I get multiple post requests from Django and Ajax on the same page working?

POST form on button click using jquery ajax

Using one function to handle multiple Ajax requests - returning same results on page load

PHP not capture $_POST data send by ajax jquery on same page

Needing to send a post using AJAX and receive the POST on the other page

Python requests - Send two requests on the same page?

Ajax multiple button click

Same button multiple click

jQuery click post multiple requests

Send multiple get requests for the same url using python

How to POST data using AJAX from one form when there are multiple forms on the same page?

multiple ajax calls on button click if page is not refreshed jquery

How to send button value to PHP backend (POST) using ajax

How to "click" a button using requests

when using SoapUI, is there a way to show multiple Requests on the same page?

multiple ajax requests on one page

Redirect two page on single button click with POST data using jQuery

Send post form to the same page using php or html only

Post and download in the same button click?

removing users from page on button click using ajax technology

Delphi - indy send post using multiple IdHTTP in the same time

On button click- do a redirect and ajax post submit form of new page, with data passed from click

How to send multiple POST requests in JavaScript

send multiple dict in payload in a post requests fails

Multiple click slideshow on same page