Storing a JavaScript variable in a MySQL database using AJAX and JSP

I'm on a mission to understand ajax and I have my sights set on saving the timeSpentOnPage value from the TimeMe.js library into my MySql database. I've successfully integrated the javascript library into my jsp page, like so:

<script type="text/javascript" src="<c:url value="/resources/js/timeme.js" />"></script>
<script type="text/javascript">
        TimeMe.initialize({
                currentPageName: "listing", // current page
                idleTimeoutInSeconds: 30 // seconds
        });     
</script>

There's an example provided on the github page for making an http request and utilizing the timeSpentOnPage variable:

window.onbeforeunload = function (event) {
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("POST","ENTER_URL_HERE", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
    xmlhttp.send(timeSpentOnPage);
};

I'm seeking guidance on how I can incorporate the timeSpentOnPage variable into my database using ajax. Any insights or advice would be greatly appreciated.

Many thanks in advance!

Answer №1

Make sure to specify the server-side technology you are utilizing, such as servlets or PHP.

If you are working with servlets, begin by creating a servlet and directing the AJAX request to the post method of that servlet like this:

xmlhttp.open("POST","Your Servlet Name", true);

To retrieve the data in the servlet, use the following code snippet:

request.getParameter("timeSpentOnPage");

With this servlet, you can then insert data into the database either through a DAO or directly based on your requirements.

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

Unable to deploy the Firebase function to Firebase functions platform

I've been watching Doug's video on YouTube for guidance on changing a message with functions in JavaScript. To resolve the error message 'types can only be applied to ts files,' I installed the Flow language script. Thankfully, that err ...

What methods are available for incorporating variables into an update query?

$b=number_format($number[12],2); $sql01=mysql_query("UPDATE t_maindbfordashboard SET valueVar=".$a." WHERE managementName=dds"); Without a doubt, I have confirmed that there are no issues with the database connection. Running the query "SELECT * FROM tabl ...

The AJAX response indicates data.Success as false even though there is data present in the response

The issue I am facing involves the JQuery Form Plugin and IE 11. For some reason, "data.Success" is returning false even though there is valid JSON in the response, confirmed through network tracing with IE Developer Tools. Upon making an initial AJAX POS ...

Utilizing environment variables in a Rails-AngularJS (1.5) project

Currently working on a Rails-AngularJS (1.5) project and encountering difficulties accessing my ENV variables in the JavaScript components such as services and console. I've implemented dotenv, stored my SECRET_KEY in a .env file, and included the fo ...

What is the best way to manage json-parse errors in a node.js environment?

After countless hours of research, I am still unable to find a solution to my seemingly simple and common problem: In Node.js using Express, I want to retrieve JSON-data via http-POST. To simplify the process, I intend to utilize the app.use(express.json( ...

Achieving a smooth sliding motion with the help of jQuery animation

Here is the code snippet: In HTML: <div> <div id="div1">12345</div> <div id="div2">67890</div> <div id="div3"><a href="#" id="slide">abcde</a></div> <div id="pad" style="display:non ...

Arranging pre-selected checkboxes in MUI Datatable

I noticed that the checked data is appearing at the top of MUI data tables without any sorting. Checkbox In this image you can see that all the checked boxes are mixed up without any order. I would like to have all the checked rows displayed together and ...

404 Response Generated by Express Routes

Exploring the MEAN stack has been a great way for me to expand my knowledge of node and express. Currently, I am working on creating a simple link between two static pages within the app. My routes are set up as follows: //Home route var index = require( ...

issue with ng-selected in AngularJS not functioning

<select ng-model="dayOfMonth"> <option value="" label="Select day"></option> <option ng-selected="parseInt(dayOfMonth) === parseInt(day+1)" ng-repeat="day in getTotalDays() track by $index" value="{{$index+1}}>{{$index+1 | or ...

Providing static content within the generated code structure by Yeoman for the Angular Fullstack framework

I'm sticking to the code structure generated by Yeoman for an Angular fullstack application. The issue I'm facing is how to include a script called core.js in a file named app.html. <script src="core.js"></script> I can't fi ...

How can you incorporate a variable into data retrieved from SQL using PHP?

I need to retrieve values from a MySQL database and dynamically echo them in PHP using a current variable. For example: $source = "TEST", $sql="SELECT * FROM data ORDER BY RAND()"; $result = mysqli_query ($connection,$sql); if(mysqli_num_rows($result)!= ...

Utilizing Parameters in ExpressJS after Querying Data

i'm currently building with expressJS and postgresql How can I retrieve a parameter after querying the result in expressJS outside of function? here's my code snippet: const checkMail = function(regEmail){ pool.query("SELECT * FROM tb_u ...

Utilizing radio type as a button while excluding the need to submit a form

I have implemented radio type buttons in my form: <div class="d-block"> <div class="btn-group" role="group" aria-label="Basic example"> <button type="radio" name="type" value= ...

subscriptions to behavior subjects may not function properly across all components

When setting up my global service, I instantiate a BehaviorSubject variable dataWorkflowService: export class CallWorkflowService { url = 'http://localhost:3000/'; selectedNode : BehaviorSubject<Node> = new BehaviorSubject(new Node(&a ...

Using Jquery toggleClass on a specific icon without impacting the other icons that share the same class

I am currently working on a project where I have multiple divs that each contain an SVG as a background image, specifically for audio player buttons. My goal is to toggle the class of the clicked element without affecting the others. However, I am struggli ...

Having difficulty retrieving AJAX POST data

I'm attempting to generate a calendar using php but I'm having trouble figuring out how to update the displayed month using ajax Within my code, I have two buttons inside a 'button' tag with values of "+1" and "-1" respectively, both w ...

Am I following the right approach for implementing Dependency Injection in Node.js?

Recently embarking on a new node project, I encountered a dependency injection issue with my fresh module as a Test-Driven Developer. Here's how I resolved the problem using an approach that involves vows for BDD testing and Sinon. The module in ques ...

What is the best way to implement a dropdown in MUI and React that displays functional components as items?

Here is a list of dummy components: const OwnerList = () => { return ( <Box sx={{ display: 'flex', }} className="owner-container" > <Avatar src='https://hips.hearstapps.com/hmg- ...

Unlocking the Secrets of Printing MySQL Data

I am currently faced with the challenge of displaying an MySQL table on screen with a border using PHP, but being new to PHP, I'm struggling. Here is what I have attempted so far: <?php ini_set("display_errors","on"); $dsn='mysql:host=localho ...

Tips on working with an array received from a PHP script through AJAX

I've been stuck with this issue for the past few hours and I'm hoping to find a solution here. What I'm attempting to do is something like the following: PHP: $errorIds = array(); if(error happens){ array_push($errorIds, $user['user ...