Having trouble getting jsp to work with ajax

I'm currently learning web design through a co-op position at a company. Unfortunately, the department I am placed in lacks experts in web design. Nevertheless, I am determined to make it work.

My current project involves creating a website that will streamline PTO management for the department. I plan to incorporate ajax into the main page which will feature a calendar system for managers to view PTO requests week by week. To practice integrating ajax, I am starting with the "add Employee" page.

However, I am facing some challenges and can't seem to identify what is missing or why my code isn't functioning as expected.

The objective of the "add Employee" page is simply to add a new employee to the database without any display required. The main page consists of four text fields where I extract information from using JavaScript:

    var firstName = document.getElementById("firstNameField");
var lastName = document.getElementById("lastNameField");
var manager = document.getElementById("managerField");
var networkID = document.getElementById("networkIDField");

So far, everything seems straightforward.

My ajax code setup includes the following steps (gathered from my research):

 var url = "addEmpJSP.jsp?firstNameField=" + escape(firstName)+"&lastNameField="+escape(lastName)+"&managerField="+escape(manager)+"&networkIDField="+escape(networkID);
  xmlhttp.open("POST",url,true);
  xmlhttp.onreadystatechange=dummy;
  xmlhttp.send(null);

This part is where I assume everything is correct, but being still relatively new to ajax, I'm unsure if I need to handle a response or if the called JSP file will automatically execute the necessary actions.

The JSP file is structured like this:

<%

ResultSet rsEmpl;
Connection connection1 = getDBConnection();
Statement statment1=connection1.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);

String fName = request.getParameter("firstNameField");
String lName = request.getParameter("lastNameField");
String manager = request.getParameter("managerField");
String networkID = request.getParameter("networkIDField");
Int empId = 0;

String EditEmplSQL = "select * from PTO_employee";
rsEmpl=statment1.executeQuery(EditEmplSQL);


rsEmpl.last();
empId = rsEmpl.getRow() - 1;


statement1.execute("INSERT INTO PTO_employee VALUES ("+empID+","+lName+","+fName+","+0+","+2+","+networkID);

%>

There's a button on the page that triggers the JavaScript function containing the ajax information. Currently, I am avoiding jQuery to focus on understanding the concepts before relying on shortcuts. My goal is to gain a thorough comprehension of web development as I pursue a degree in Software Engineering. If you require additional information, feel free to ask. Apologies for any confusion caused by my lack of expertise in this area.

Answer №1

The main page consists of only 4 text fields, which can be accessed in JavaScript like this:

var firstName = document.getElementById("firstNameField").value;
var lastName = document.getElementById("lastNameField").value;
var manager = document.getElementById("managerField").value;
var networkID = document.getElementById("networkIDField").value;

In the provided code snippet, instead of using escape(), it is recommended to use encodeURIComponent() for URI component encoding.

The JSP file contains lines such as:

...
int empId = 0;
...

It seems there are syntax errors; make sure to use correct data types and follow proper coding practices. Additionally, consider utilizing DB sequences or auto-increment IDs for more efficient database operations.

...
statement1.execute("INSERT INTO PTO_employee VALUES (" + empID + ",'" + lName + "','" + fName + "'," + 0 + "," + 2 + ",'" + networkID + "'");
...

Ensure to enclose string values in quotes within SQL queries to prevent potential vulnerabilities. It is essential to address SQL injection risks and properly manage database resources to avoid crashes.

Lastly, monitor server logs for compile errors and exceptions, and pay attention to ajax response details to understand and resolve any issues effectively.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for dynamically adding and removing keys from a JSON object

I am working on a code for a car rental website using jQuery mobile. I need to dynamically add and remove keys from a JSON object with true or false values. The goal is to make a selected car unavailable by changing the "available" key to either true or ...

Triggering a click event on a radio input type using jQuery

I am having trouble assigning an event to a radio button. Despite searching for solutions online, I haven't been able to find anything that works. The latest solution I attempted involved the following code: $(document).ready(function() { $("#mo ...

Send unprocessed HTML content using AJAX to the server with ModSecurity enabled

I have a website that utilizes jQuery ajax $.post to store html content in a PHP script. The content being sent via $.post is serialized data from a textarea form (in which users make changes to css, javascript & html). Everything functions properly ...

"Error: Unable to access the property '$emit' of an undefined value" - VueJS

I'm currently working on implementing a basic authentication system in vuejs. I have a set of objects containing valid usernames and passwords. I am looping through this list to validate the entered username and password. If there is a match, I trigge ...

Creating an HTML string from an array in JavaScript

Hi there, I'm in need of some assistance with a JavaScript task. Can anyone help? I'm looking to create a JavaScript function that can take an array and return the corresponding HTML string. For example: [tagName, child1, child2, ...] • The ...

What is the process for establishing connections in a NoSQL database?

What is the process for establishing relationships in a NoSQL database? You can establish relationships in a Firebase database, where the database is stored in a JSON format. ...

Best practices for efficiently storing and retrieving data from a large list in PHP

Hello and thank you in advance for your assistance, I am currently faced with a challenge involving a list of one million names and their corresponding nicknames. Each name is paired with only one nickname, even if they happen to be the same. My usual ap ...

I am attempting to implement an Express static middleware as demonstrated in this book, but I am having trouble understanding the intended purpose of the example

I'm currently studying a chapter in this book that talks about Express, specifically concerning the use of express.static to serve files. However, I'm encountering an issue where the code catches an error when no file is found. I've created ...

Improving online platforms without relying on users to manually refresh

While working at my job, I am tasked with writing code for a web application that frequently receives new updates on the servers. However, we have encountered an issue where some users tend to keep the application open in their browser window for days at a ...

Is there a way to stop mouse panning in ThreeJs OrbitControls without affecting the ability to pan using keys?

My goal is to prevent users from panning with their mouse while still allowing them to pan using the keys. When I use controls.enablePan = false;, it disables key panning as well. Trying to rebind the mouse buttons requires me to assign a button to Orbit ...

Updating the current date at midnight or on the new day in JavaScript can be achieved using specific date and time

I have a web watch that is supposed to work 24/7 and display the digital time along with the current day. However, my issue is that when the time passes midnight, the current day does not update and I am forced to restart the entire application. I attempt ...

Rails Navigation Issue: JQuery Confirmation Not Functioning Properly

Having a Rails app, I wanted to replicate the onunload effect to prompt before leaving changes. During my search, I came across Are You Sure?. After implementing it on a form, I noticed that it only works on page refreshes and not on links that take you a ...

What could possibly be causing this peculiar behavior of an AJAX post request in Node.js Express by executing a GET request with the data just before the actual post request is

I'm facing an intriguing challenge. I have a form where I intend to implement ajax to perform a post request on the server. replyPrefix = "<div id='addCommentContainer'><form class='addCommentForm' name='addcomment&a ...

Utilizing useState() to manage active link state in Navigation bar component

Learning react and new to the framework. Trying to create a responsive navbar component with material-ui. Works fine on medium devices but struggling with updating active link on smaller devices. Navbar.js ... SideDrawer.js ... C ...

Cordova 3.0 doesn't support Ajax functionality on the Galaxy S4

Recently, I started working with Cordova and jQuery Mobile. Despite following several guides and forum posts, none of them seem to be helping with my issue. I created a test app with an ajax call that returns values. Surprisingly, it works perfectly on som ...

Can JSON be used to perform mathematical operations and calculations?

Utilizing the amazing json-server as my application's backend has been incredibly beneficial for custom data retrieval. However, it would be even more valuable if it supported calculations and expressions to mimic backend behavior. Consider this data ...

Is there a way to switch the video source when a particular h3 tag is clicked?

https://i.sstatic.net/I2gIZ.jpgI'm currently working on building a video streaming site, but I've hit a roadblock. My challenge right now is figuring out how to make the episode selector change the video player's source. I'm a bit conf ...

Multer in NodeJS is malfunctioning

I attempted to implement file upload functionality using NodeJS, ExpressJS, and Multer but encountered issues. The version of ExpressJS I am using is 4.12.3 Below is a snippet of my source code: server.js: var express = require('express'), ...

Transform milliseconds into an ISODate representation

I have a MongoDB collection where records are stored with timestamp in milliseconds. I need to aggregate these records by hour and convert the timestamp to ISODate so that I can use MongoDB's built-in date operators ($hour, $month, etc.) Here is an e ...

Using the OR condition in the ternary operator within ReactJS

Recently, I have started working on a ReactJS project focusing on menus. In this project, I have successfully implemented logic for the active menu feature. For instance, when a user is on page 2, the corresponding menu item will be highlighted as active. ...