I am aware of using AJAX calls to refresh content inside a div
using the response received, but in my case I have no response but still want to refresh the div.
My application has a table called ‘Cart’, on which when I click the delete button, it removes an item from the cart. I remove the item by sending an AJAX call to the Java servlet that updates the cart in an ArrayList. As I’m removing only one object, I dont have a response, but still want to update the cart with the removed item.
I have tried the following ways:
-
Redirect to the same page using servlet after updating cart array. This causes the page to reload.
request.getRequestDispatcher(target).forward(request, response);
where target is index.jspx -
Use
$(..).load('index.jspx')
to try and refresh the particulardiv
, but this places the entire contents ofindex.jspx
into the tinydiv
with the cart table.
2
Answers
You actually don’t have to redirect the whole thing again. Instead of redirecting, just use
response.getWriter().write(<Your updated Array>);
insidedoPost()
ordoGet()
depending on which you are using.This will send your updated array to your AJAX code, instead of refreshing the whole page.
An AJAX request (Asynchronous Javascript And XML) is sent to your server. You can define a callback for your AJAX request, that is, a Javascript
function
that is going to be executed once the request ended. You can also use promises for this purpose. Anyway, once you know how you can execute a function AFTER the request has completed, you need to decide whether you need information from the server.If you are content with not receiving any meaningful answers from the server and are okay with assuming that the removal was successful, then you can simply remember which delete button was pressed, find the row which contains it and
remove()
it. In this case you do not need to send further requests to the server.Otherwise, if you need to get further information from the server (because new items might have been created/modified/removed), then simply change your server-side in order to send back a JSON about the items to the client-side and refresh your table there.