Learn Servlet-JSP By Building A Social Network Website — Part XV
Applying the AJAX technique to implementing add a friend feature
Task 22: Add a user to the friend list
In the previous task, we have done loading a list of suggested users so that the currently logged-in user can select ones in the list to add as his/her friends.
As you can see from the suggested list, each friend item has a “Add friend” button.
In this task, we are going to implement the “Add friend” button so that when it is clicked, the associated user will be added to the currently signed-in user’s friend list.
Once the selected user has been added, the current user’s friend list needs to be re-loaded so that the new friend appears on the list.
Step 1:
In the UserService
class, create a new method called addFriend()
with the following implementation:
Friends’ information is stored in the table tbl_friend
. This table has 3 columns but the first one is the auto-increased primary key, so we just need to put a null value as the first parameter in the insert query. The other two columns we need to explicitly supply are:
- The current signed-in user’s id which is the second parameter (the first question mark from left to right) in the insert statement
- The selected user’s id which will be added as the current user’s friend, which is the third parameter (the second question mark) in the insert statement
Step 2:
Now we need to update the suggested-friend.jsp
file to perform 2 tasks:
- When the button “Add friend” is clicked, we send a friend’s data to the server-side to add to the database
- Once a new has been added successfully, we re-load the friend list.
In suggested-friend.jsp
file, add the following <script>
tags at the end:
Since in the last task, we had added the friend id’s value to each of the id attributes of the <button>
tags, to get a friend’s id value we can use:
var friendId = $(this).attr(‘id’);
Then, we send an AJAX request with the following options:
Step 3:
In the SuggestedFriendController
servlet, update the processRequest()
method as follows:
Before adding a new friend, we do need to check if the coming action in the request is “add-friend
”. If it is, we get the friend’s id and invoke the service method to insert the data to the database:
Now everything is done. Let’s run to see if the feature is working.
You can see it in action:
Check out the complete source code if you get stuck:
https://github.com/stackera/learn-servlet-jsp/blob/main/Task22_AddFriend_AJAX.zip