Javascript Value of Variable not updating in Servlet - javascript

I have simplified my Code to breakdown the Problem and to have a simple Example with a Timestamp for whats actually going wrong.
So please not be suprised why i do a AJAX call, this is for the real functionality of the Servlet.
Its a Servlet and the follwing code is part of a JSP page, im Working on JAVA 1.7 and a Tomcat 7. I run it in Firefox and Chrome.
My goal is to retrieve a value from a Java method and write it on the servlet page into the DIV "ContentCharts".
The Problem is that Javascript does not update the vaule of "zeit" and always writes the same Timestamp into the DIV-Container and on the Console
$(document).ready(function()
{
function ausgabe()
{
<%
GregorianCalendar now = new GregorianCalendar();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
String JZeit = df.format(now.getTime());
System.out.println("FKT ausgabe zeit:"+ JZeit);
%>
var zeit='<%=JZeit %>';
console.info('Zeit:', zeit);
document.getElementById('ContentCharts').innerHTML = zeit;
}
$("#subtab2").click(function()
{
$.ajax
(
{
url:'overview',
data:{dbname:this.className},
type:'get',
cache:false,
success:function(){ausgabe();},
error:function(){alert('error');}
}
);
}
}
To test this I write the value of the JAVA varible "Jzeit" into the Serverlogs and get this (Click to see the Picture) results when I click the buttons three times. As you can see in the Picture here I get the right Timestamps.
Now I have also post the Value of the JS varialbe "zeit" into the Firebug Console. And now i get the Wrong time Stamps (Click to see the Picture)
The Content in the DIV is refreshing but here is the same Problem like in the Console, its always the same Timestamp.
These are my thoughts and Questions:
Why has the JS variable the wrong value when its right in JAVA?
Is there any option to say JS that it has to update the variable?
Could it be that JS saves the answers of the JAVA code and does not run it anymore, but runs the upper JAVA Code Snippet because there is no direct connection betwen JS and JAVA, like a value allocation?
How can i fix my Problem?
If you need more Informations to help me please ask for it.

You're a bit confused about the ajax pattern.
Note that anything you write in <%= jsp tags %> will be rendered on the server, then sent to the client where it will never change. Therefore your ausgabe function will always return the same result when it is called. Subsequent calls to the function will not make repeated server requests, which is the behavior you're observing.
To fix this, the success function in your ajax call should take an argument which will be instantiated with the response from the server. The java code you've written in the jsp tags in the ausgabe function should be moved to the server and any variables you need should be returned from the overview endpoint. Then, the ausgabe function should be refactored to take an argument containing the server-calculated values, and update your page as desired.
Here is some reading on ajax requests:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
http://api.jquery.com/jquery.ajax/

Related

How to replace php function with ajax

I am new to AJAX here. How can i replace the initial php function after the action of ajax is execute? I have found that the page will not refresh after the action is execute.
Here is the code:
javascript
function set_ddm(another_data) {
var result = $.ajax({
url: '../display/ea_form_header.php',
type: 'POST',
data: {
action: 'set_ddm',
Data_store: another_data,
},
success: function(data) {
console.log(data);
}
}).responseText;
}
php code
<td>
<?php
//initial function (customized drop down)
print ddm_jsfunc_employee("employee_list",$employee_list)
set_ddm(data);
if($_POST['action'] =='set_ddm') {
$employee_list=$_POST['Data_store'];
$employee_list_decoded = json_decode($employee_list,true);
//expected this function to replace the initial function after ajax was called
print ddm_jsfunc_employee("employee_list",$employee_list_decoded);
} ?>
</td>
I expect the function will replace the initial function and show in the main page but it only show in console after ajax(page aren't refresh to show it). Is there any wrong with the code or any solution for this? (the ddm_jsfunc_employee must be there to print the drop down)
thanks in advance
From ajax success callback you have to set that response in the html to view on web page.
like this:
$('.elementClass').html(response);
i hope this will works for you.
I think you have a slight misunderstanding about what AJAX is, it is not something to replace your PHP code with, but to asynchronously get data and update your webpage without reloading.
Let's first take a look at the .ajax function specifically interesting for us now is the .done() callback method, because JavaScript does the request realtime (async) JavaScript does not know when the request is done. But it allows us to specify a function inside the .done for it to call when it is done.
A really simple example would be:
$.ajax('https://stackoverflow.com')
.done(function(data) {
// We can do what we want with the data here.
console.log(data);
});
Now when the request is done the function we defined in .done will be called, in this case a simple log. But you would want to change this to a function that updates your HTML.
I also see you are calling JavaScript functions in your PHP, this will not work as PHP runs on your server but JavaScript runs in your browser. (Unless you use node or the likes)
Just a tip; it is advised to place JavaScript at the bottom of your HTML page as JavaScript is blocking content. (proper link explaining needed here)
Meaning your browser will stop parsing the HTML and run the JavaScript as it finds it.
Long story short, if you want to replace the PHP code, you would have to remove it. Make a PHP script which gives you your data. AJAX call it and then use .done or success and update your webpage from there.

Ajax call. Passing value to another php file

I have a problem and hope you can help.
Ii have a status.PHP file containing a js.
STATUS.PHP
<? ..stuff... ?>
<html>
<head>
<title>BCM Status Page</title>
<script src="jquery-3.3.1.min.js"></script>
<script src="updater.js"></script>
</head>
<body bgcolor="#305c57" onload='init();'>
As you can see in the html ihave included a JS, during "onload" i'm calling the init() function of the javascript called updater.js
Now in the UPDATER.JS
function init() {
setInterval(read, 2000)
}
function read() {
$.ajax({
type: 'POST',
url: 'readDB.php',
dataType: 'jsonp',
success: function (data) {
console.log(data);
var json_obj = $.parseJSON(data);
console.log(json_obj[0].gwnumber);
},
error: function () {
console.log("Error loading data");
}
});
}
I'm doing an ajax call to the readDB.php that is working as intended, infact i have the correct value in the json_obj.
My question is: how can i get the json_obj value and pass it to the status.PHP file that is the one who's including the JS too?
Hope you can help. TY
Ok, there is a lot to say in this argument, but i will be the briefiest possible.
first things first
php and Javascript are two different programming language with a completely different paradigm.
The first is a back-end focused programming language;
Javascript instead is more front-end focused, just for entirety i have to mention that JS is used also for the backend part with a special eviroment called Node.js
back to the problem, the things that you are trying to do is not impossible but is excactly as you asked, your're idea (if i got it) was to pass the data from the js to the php like a parameter in a function...
the thing is that the php is elaborate and renderizated before in the server and the javascript is executed in the client, in the client web page there is no more footprint the php. This process is described very well at this link: http://php.net/manual/en/intro-whatis.php
The possible solution is:
FRONT-END(js): make another ajax call(request) to the same page that you are displaying with all the data that you want to elaborate.
BACK-END(php): controll if this request has been made, then access the data with the global variables $_POST & $_GET (depending on the type of the request), then elaborate this data.
if I can I suggest you to make a check if the manipulation that you want to do on those data need to be done in the server-side and not by the js!
Consider the order of execution:
User visits status.php
Browser requests status.php
Server executes status.php and sends response to browser
JS requests readDB.php
Browser requests readDB.php
Server executes readDB.php and sends response to browser
JS processes response
Go To 4
By the time you get to 7, it is too late to influence what happens at step 2.
You could make a new Ajax request to status.php and process the response in JS, but since status.php returns an entire HTML document, that doesn't make sense.
You could use location to load a new page using a URL that includes status.php and a query string with information from the Ajax response, but that would making using Ajax in the first place pointless.
You should probably change readDB.php to return *all** the data you need, and then using DOM methods (or jQuery wrappers around them) to modify the page the user is already looking at.
The simpliest and fastest (maybe not the sexiest way) to do it :
create global variable var respondData; in STATUS.PHP
within you ajax request on success function assign your data callback to it
respondData = data;
Now you have an access to it from every place in your code even when the ajax request is done. Just bare in mind to ensure you will try to access this variable after the page will fully load and after ajax will process the request. Otherwise you will get 'undefined'

Increment the number of times an article has been read

I have a situation where I need to increase the number of time article has been read.
Once someone opens an article it should be reflected in the database by incrementing number of reads by one. Simple.
Sending POST request to the server increments the number of reads by one. The article in question is supplied via URL parameter.
Doing it manually by typing the URL in a browser works as expected. So server side is not at fault.
My problems start with the javascript side of it or rather jquery. I hook the event to the article link. So every time a user clicks on the article link it increments the number of reads like so:
$('#list-articles .article-link').click(function(e){
var oid = $(this).parent().parent().attr('data-oid').toString(); //Get the article id
$.post( "/articles/viewed/" + oid );
});
Now this does not work! Number is not increased.
I don't prevent default action since I need the link to actually open and display the article.
Now if I put an alert right after the post like this:
$('#list-articles .article-link').click(function(e){
var oid = $(this).parent().parent().attr('data-oid').toString(); //Get the article id
$.post( "/articles/viewed/" + oid );
alert(oid);
});
This variant works. After I dismiss the alert window, the number is incremented. Why is this so?? How can I fix this to actually work without the alert event present?
UPDATE
Thank you for helping to solve this. All answers are great and help one way or another. The only variant that works so far is disabling async on ajax call. It would be great if someone could elaborate on why switching the async mode off in ajax fixed it. So the post request in the original was never executed? If I was simply checking too early and the number increase was not visible upon page load, it should be still visible on the next page reload, right? SInce it wasn't updated on the database at all I assume that post was not run at all. Why is this so? I want to understand the issue so I do't get into this problem again. Thanks.
Your problem could be due to $.post being asynchronous and you checking this too soon and try posting synchronously:
$.ajax({
type: 'POST',
url: "/articles/viewed/" + oid,
async:false
});
Prevent default. Wait for the response from the server to say incrementing article reads by 1 was successful, then redirect to the article.
If it works with the alert in place it sounds like a race condition.

how to assign a javascript variable to a jsp string variable?

i m doing a database project using mysql as the database and jsp for my frontend part along with javascript and ajax for interaction.
Now the problem is i need to assign a java script variable which is having a string to a jsp variable.
I did this using the following statement?
<% String str="document.write(s)"; %>
where "s" is already defined as
<script type="text/javascript">
var s="hello world";
<script>
but i m getting error in the assignment statement(which is shown in bold above) as incorrect syntax?
the error i m getting is-
check the manual that corresponds to your MySQL server version for the right syntax to use near '<script>document.write(s)</script>'
what is the error in this stmt or is there any other method in doing this assignment?
Can anyone help in doing this?
You cannot do this. The JSP statement is executed server-side, before the execution of the Javascript statement, that is executed client-side after the browser received the http response.
It is not clear your goal, but if you only need to display in the page the value of a javascript variable, you can use:
trivial javascript:
document.write(s);
targeting existing element:
document.getElementById('myElementId').innerHTML = s;
using jQuery:
$('#myElementId').html(s);
If i understand correctly you are trying to build and execute a sql query based on user input that is handled by javascript. As ADC said this can not be done since jsp is executed server side therefore before browser executes javascript. What you can do is create the sql query and pass this as a parameter a different jsp/servlet (or the same if you can handle this case) which will execute the query
In the first page where sql statement is constructed in variable s you should put something like this
<script>
var s = "hello world";
function createLink(){
document.getElementById('mylink').href= 'page2.jsp?statement='+s;
}
window.onload=createLink;
</script>
<a id="mylink" href=""/>Click to exexute query</a>
which create a link to you second page (page2.jsp) passing the statement as parameter.
Now in page2.jsp you should retreive the parameter value like
<% String statement = request.getParameter("statement") %>
and then execute your query.
Even better you should use a servlet instead of a jsp page to perform the query. You could read a tutorial for jsp/sevlets to see how this can be done
eg. http://www.laliluna.de/articles/posts/first-java-servlets-jsp-tutorial.html

Pass data to database using javascript Onclick

I am a real noob when it comes to javascript/ajax, so any help will be very appreciated.
In reference to this question:
Updating a MySql database using PHP via an onClick javascript function
But mainly concerned with the answer left by Phill Sacre. I am wondering if someone could elaborate on how we are(if we can?) passing values/data through his example, using jquery.
The code example left by him is as follows:
function updateScore(answer, correct) {
if (answer == correct) {
$.post('updatescore.php');
}
}
...
<a onclick="updateScore(this, correct)" ...> </a>
Say for example, we are wanting to pass any number of values to the database with php, could someone give me a snippet example of what is required in the javascript function? Or elaborate on what is posted above please?
Thanks again all.
The simplest example I can think of is this. Make your AJAX call in your if block like this:
$.get('updatescore.php', {'score': '222'}, function(d) {
alert('Hello from PHP: ' + d);
});
On your "updatescore.php" script, just do that: update the score. And return a plain text stating wether the update operation was successful or not.
Good luck.
P.S.: You could also use POST instead of GET.
What you would do is on the php server side have a page lets say its update.php. This page will be visited by your javascript in an Ajax request, take the request and put it in a database.
The php might look something like this:
<?php
mysql_connect(...)
mysql_query("INSERT INTO table
(score) VALUES('$_GET["score"]') ")
Your javascript would simply preform an ajax request on update.php and send it the variables as get value "score".
Phil is not passing any values to the script. He's simply sending a request to the script which most likely contains logic to 'update' the score. A savvy person taking his test though could simply look at the HTML source and see the answer by checking to see what the anchor is doing.
To further nitpick about his solution, a set of radio buttons should be used, and within the form, a button or some sort of clickable element should be used to send the values to the server via an ajax request, and the values sent to the server can be analyzed and the status of the answer sent back to the page.
Since you're using jQuery, the code can be made unobtrusive as seen in the following example:
$('#submit_answer').click(function() {
var answer = 'blah' // With blah being the value of the radio button
$.get('updatescore.php',
{'value': answer},
function(d) {
alert('Your answer is: ' + d') // Where d is the string 'incorrect' or 'correct'
}
});
Enjoy.

Categories