how can we apply validation in a jsp page - java

I have written the following code but its not working. Can you please help me.
Though these solutions are available everywhere but still the code is not working.
<div align="center">Registration Form</div>
<script type="text/javascript">
function validate()
{
var name = document.myform.name.value;
var password = document.myform.password.value;
var email = document.myform.email.value;
var mobile = document.myform.mobile.value;
if(name.equals(""))
{
alert("Enter name");
return false;
}
else if(password.equals(""))
{
alert("Enter password");
return false;
}
else if(email.equals(""))
{
alert("Enter email-id");
return false;
}
else if(mobile.equals(""))
{
alert("Enter mobile no.");
return false;
}
else
{
alert("Submitted");
return true;
}
}
</script>
<body>
<form name ="myform" method="post" onsubmit = "return validate()">

JS String does not have method/prototype .equals().
Seems like you have mistaken with Java's String#equals(). Replace your code name.equals("") with name === "" instead or just name.length === 0 and so on for the rest.
For debugging purpose keep open developer console open, from browser press F12, there you will get those errors.

Related

How to pass user entered data in a web form and pass it into a Java Script function

I am trying to take the inputed value from here:
index.html
<form name="ytenter" action="youtbe.html" method="get">
url: <input type="text" id="url"name="url">
stop <input type="text" id="stop" name="stop">
<input type="submit" value="Submit" onclick="ytstop(this.stop)">
</form>
and take the entered value in id=url and id=stop
and run it to youtbe.html here:
<head>
<script>
(function ytstop() {
var stopPlayAt=10; // Stop play at time in seconds
var stopPlayTimer; // Reference to settimeout call
// This code loads the IFrame Player API code asynchronously.
var tag = document.createElement("script");
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
window.onYouTubeIframeAPIReady = function () {
player = new YT.Player("player", {
"height": "315",
"width": "560",
"videoId": "L6cVcbkx8l8",
"events": {
"onReady": onPlayerReady,
"onStateChange": onPlayerStateChange
}
});
}
// The API will call this function when the video player is ready.
// This automatically starts the video playback when the player is loaded.
function onPlayerReady(event) {
event.target.playVideo();
}
// The API calls this function when the player's state changes.
function onPlayerStateChange(event) {
var time, rate, remainingTime;
clearTimeout(stopPlayTimer);
if (event.data == YT.PlayerState.PLAYING) {
time = player.getCurrentTime();
// Add .4 of a second to the time in case it's close to the current time
// (The API kept returning ~9.7 when hitting play after stopping at 10s)
if (time + .4 < stopPlayAt) {
rate = player.getPlaybackRate();
remainingTime = (stopPlayAt - time) / rate;
stopPlayTimer = setTimeout(pauseVideo, remainingTime * 1000);
}
}
}
function pauseVideo() {
player.pauseVideo();
}
})();
</script>
</head>
<body>
<div id="player">
</div>
</html>
I need to take the "stop" from the form and put it into stopPlayAt VAR at the top
Then I need to take "url" entered from the form and put it into "videoID":
Thanks for your help. Just want the end product to allow youtube link to be entered and a time to be entered and it runs it until that time entered in seconds.
I would like to refer you to the top answer on this page:
How to get the value from the GET parameters?
This enables you to get the value of the GET-parameters in the URL.

Counting Number of attemps left using ajax

My problem is as follow :
I am making an ajax call to a jsp and its success part is like this :
success: function(msg){
alert(msg);
if(msg.indexOf("false")>=0)
{
var counter=$('#attemptsleft').value+1;
$('#attemptsleft').val(counter);
var left=3-counter;
if(left>=0)
alert("You have "+left+" attemps left");
else
alert("You have no attempts left");
}
else{
alert("success");
}
}
Actually what i want to do is that to provide number of attempts to the user and if he exceeds those then tell that their are no more attempts left.
In html am doing this :
<input type="hidden" id="attemptsleft" value="0"></input>
Where am doing wrong.As am not getting results which were expected.
You aren't checking the condition when deciding whether to give success.
As an aside, you can just store the attempts value in a javascript variable, instead of using an input.
Try this one :
success: function(msg){
alert(msg);
if(msg.indexOf("false")>=0)
{
var counter=parseInt($('#attemptsleft').value)+1;
$('#attemptsleft').val(counter);
var left=3-counter;
if(left>=0)
alert("You have "+left+" attemps left");
else
alert("You have no attempts left");
}
else{
alert("success");
}
}
I just added a parseInt() while increment the attempts left value.

Detect java version using deployJava.js ,pops up java upgrade menu

I have a need to know the java version installed on client machine, have come up with the solution here
How to write JavaScript function to check JRE version
When I tried, got with the answer:
console.log(deployJava.getJREs());
But at the address bar, pop up menu is displayed like this
How to hide this?.
If this can not be achieved, please suggest any other idea to implement, as this can not be used,if this popup is not suppressed
I am pretty sure from recent experiments that there is no way to suppress it. For the script to detect the plug-in versions, it must invoke the plug-in itself.
After those experiments I worked to create a script that could detect a variety of things out about the Java plug-in without invoking the plug-in itself. They relied on examining the mime-types info.
This still shows a warning in IE if opened from the local file-system. But I hope it will be more forgiving if loaded from the internet. Please report back.
But note this is what it reports for IE when the 'allow scripts' check is OK'd.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Java Information - Non Deployment Toolkit Script</title>
<meta name='author' content='Andrew Thompson'>
<meta name='description' content='Non Deployment Toolkit Script'>
<script src='mimetypes.js'></script>
<style type='text/css'>
.true {
background-color: #6F6;
}
.false {
background-color: #FB0;
}
.undefined {
background-color: #FF0;
}
.datum {
font-family: monospace;
}
td {
padding: 4px;
}
</style>
</head>
<body>
<h1>Java on this PC</h1>
<h2>Overview</h2>
<p>This page endeavors to ascertain the installation, availability
& version of the Java installed on the client PC.
More importantly, it attempts to discover the information <b>without
invoking the Java Plug-In</b> itself.
The last part is what makes it different
to the Deployment Toolkit Script supplied by Oracle.
</p>
<script type='text/javascript'>
document.write("<h2>Browser Info.</h2>");
document.write(getBrowserInfo());
document.write("<h2>Basic Info.</h2>");
document.write("<table border='1'>");
document.write(get3CellRow('<b>Enabled</b>', isJava(), 'Java is enabled (1.1+) - IE info. (short of ActiveX) stops here'));
document.write(get3CellRow('<b>Version</b>', getVersion(), 'Maximum version reliably <em>known</em> to be available'));
if (isIE()) {
document.write(get3CellRow('<b>MSIE</b>', getIEVersion(), 'Maximum version reliably known to be available in IE, tested using ActiveX'));
}
document.write(get3CellRow('<b>JWS</b>', isJWS(), 'Java Web Start available (1.4.2+)'));
document.write(get3CellRow('<b>Plug-In 2</b>', isPlugin2(), 'Plug-In 2 available (1.6.0_10+)'));
document.write("</table>");
if (plugins.length>0) {
document.write("<h2>Navigator Plug-Ins</h2>");
document.write("<table border='1'>");
document.write("<tr><th>Name</th><th>Version</th><th>File Name</th><th>Description</th></tr>");
for (var ii=0; ii<plugins.length; ii++) {
var t = plugins[ii].name;
if (t.indexOf("Java")>-1) {
document.write("<tr>");
document.write("<td>" + plugins[ii].name + "</td>");
document.write(getDataStyledCell(plugins[ii].version));
document.write("<td>" + plugins[ii].filename + "</td>");
document.write("<td>" + plugins[ii].description + "</td>");
document.write("</tr>");
}
}
document.write("</table>");
}
if (mimes.length>0) {
document.write("<h2>Navigator Mime-Types</h2>");
document.write("<table border='1'>");
document.write("<tr><th>Mime</th><th>Description</th><th>Types</th></tr>");
for (var ii=0; ii<mimes.length; ii++) {
var t = mimes[ii].type;
if (t.indexOf("java")>0 &&
((t.indexOf("jpi")>0 || t.indexOf("deploy")>0 || t.indexOf("jnlp")>0 || t.indexOf("vm")>0) ||
mimes[ii].description.length>0)
) {
document.write("<tr>");
document.write("<td>" + mimes[ii].type + "</td>");
document.write("<td>" + mimes[ii].description + "</td>");
document.write("<td>" + mimes[ii].suffixes + "</td>");
document.write("</tr>");
}
}
document.write("</table>");
}
</script>
<hr>
<h2>Description</h2>
<p>In order (if available) the information is:
<ul>
<li><b>Browser info. Table:</b> Not strictly related to Java - the
information in the other tables is determined without
further reference to any information shown in this table (except for the <code>appName</code> used for
identifying IE).
OTOH it is an helpful guide
as to what we should be <em>expecting</em>
from the other information. E.G. IE
will not show the Plug-In or Mime Type tables. <em>Only</em>
FF displays the plug-in version numbers.
</li>
<li><b>Basic info. Table</b>
<ul>
<li><b>Enabled</b>: Java is known to this browser and enabled, according to JavaScript <code>navigator.javaEnabled()</code>.</li>
<li><b>Version</b>: The maximum Java version known to be supported in this browser/PC.
It is set to <code>1.1</code> if the previous check is <code>true</code>, since the MSVM
was the first Java version the public could get in a browser, and the MSVM
implemented Java 1.1. Goes on to check
<code>application/x-java-applet;jpi-version</code>
in the mime types if available
(i.e. typically browsers that are <em>not</em> IE).
</li>
<li><b>MSIE</b> (IE Only): The maximum Java version known to be supported by this instance of Internet Explorer
as determined using ActiveX. It runs from 1.4.2, 1.5.0.. through 1.9.0.
</li>
<li><b>JWS</b>:
Inferred from a comparison of the version to the Sun JRE in which
it was co-bundled.</li>
<li><b>Plug-In 2</b>:
Inferred from a comparison of the version to the Sun JRE in which
it was introduced.</li>
</ul>
</li>
<li><b>Navigator Object Tables:</b>
<em>The rest of the info. is gleaned from the <code>navigator</code> object.
IE does not include this information.</em>
<ul>
<li><b>Plug-Ins</b>: More details of the Java related plugins.
Filtered for <code>Java</code> in the <code>name</code>.
A <code>description</code> showing "Next Generation Java Plug-in" or <code>name</code>
"Java Deployment Toolkit" should be 1.6.0_10+.</li>
<li><b>Mime-Types</b>: More information on the Java related Mime-Types.
Filtered in <code>mime</code> field for <code>'java'</code> + <code>('jpi'||'vm'||'deploy')</code>
or a non-empty <code>description</code>.
The value <code>java-deployment-toolkit</code> in the <code>mime</code>
is a good indicator of 1.6.0_10+.
</li>
</ul>
</li>
</ul>
</body>
</html>
mimetypes.js
// As a version string, this might be '1.4.2_31'.
// I.E. it is not a 'number' but a 'string' and therefore must be treated as a string.
var highestVersion = 'undefined';
var mimes = window.navigator.mimeTypes;
var plugins = window.navigator.plugins;
function isJava() {
return (
typeof(navigator.javaEnabled) !== 'undefined' &&
navigator.javaEnabled());
}
function getVersion() {
var version = 0;
if (isJava()) {
version = 1.1;
}
for (var ii=0; ii<mimes.length; ii++) {
var t = mimes[ii].type;
if (t.indexOf("java")>0 &&
t.indexOf("jpi")>0 &&
t.indexOf("applet")>0
) {
var parts = t.split("=");
version = parts[parts.length-1];
}
}
if (highestVersion=='undefined') highestVersion = version;
return version;
}
function isJWS() {
var ver = highestVersion;
var className = false;
if (ver>'1.0') {
className = undefined;
}
if (ver>'1.4.2') {
className = true;
}
return className;
}
function isPlugin2() {
var ver = highestVersion;
var className = false;
if (ver>'1.0') {
className = undefined;
}
if (ver>'1.6.0_10') {
className = true;
}
return className;
}
var versionFamily = [
'1.9.0', '1.8.0', '1.7.0',
'1.6.0', '1.5.0', '1.4.2'
];
function getIEVersion() {
for (var i=0; i<versionFamily.length; i++) {
if (testUsingActiveX(versionFamily[i])) {
return versionFamily[i];
}
}
return false;
}
if (isIE() && getVersion()=='1.1') {
highestVersion = getIEVersion();
}
function isIE() {
return navigator.appName=='Microsoft Internet Explorer';
}
function testUsingActiveX(version) {
var objectName = 'JavaWebStart.isInstalled.' + version + '.0';
// we need the typeof check here for this to run on FF/Chrome
// the check needs to be in place here - cannot even pass ActiveXObject
// as arg to another function
if (typeof ActiveXObject == 'undefined' || !ActiveXObject) {
alert('[testUsingActiveX()] Browser claims to be IE, but no ActiveXObject object?');
return false;
}
try {
return (new ActiveXObject(objectName) != null);
} catch (exception) {
return false;
}
}
function get3CellRow(cell1, cell2, cell3) {
var s = "" +
"<tr>" +
"<td class='" +
getClassName(cell1) +
"'>" +
cell1 +
"</td>" +
getDataStyledCell(cell2) +
"<td class='" +
getClassName(cell3) +
"'>" +
cell3 +
"</td>" +
"</tr>" +
"";
return s;
}
function getDataStyledCell(value) {
var s = "<td class='datum " +
getClassName(value) +
"'>" +
value +
"</td>";
return s;
}
function getClassName(val) {
var className = undefined;
if (
(val) ||
(!val) ||
(val!=="undefined")
) {
className = val;
}
return className;
}
function getBrowserInfo() {
var s = "";
var props = [
'appCodeName','appName','appVersion',
'userAgent',
'platform','cookieEnabled'
];
s += "<table border='1'>";
for (var i=0; i<props.length; i++) {
s+= "<tr>";
s+= "<td><b>";
s+= props[i];
s+= "</b></td>";
s+= "<td>";
s+= navigator[props[i]];
s+= "</td>";
s+= "</tr>";
}
s += "</table>";
return s;
}
Please note (be warned) this script was written by me, a Java programmer. Java programmers are typically the absolute worst people on the planet for writing JS, since we foolishly tend to presume. "It's JavaScript, how hard can it be?".
To write really good JavaScript is indeed an art.
Even worse, this was experimental code that was 'hacked out' with the intention of improving it later, but the project was abandoned and 'later' never arrived.
Caveat emptor.

Unable to call a function with ENTER key

I need to pass in some values to my function
I want the function to run when I press ENTER KEY in PHP
the function is update()
This is my PHP
echo '<input type="text" size="23" id= n'.$row["ContactID"].'
class = "name" placeholder="Contact Name"
value="'.$row["Name"].'
onkeydown="if (event.keyCode == 13) updatename(this,'.$row["ContactID"].') ">';
my javascript
function updatename(item, cid)
{
var varname = $(item).val();
var originaltext = $(item).val();
$.ajax({
url: 'changeContact.php',
type: 'POST',
data:{
varname: varname
},
success:function (data) {
if (data == '1')
{
$("#status")
.addClass("success")
.html("Data saved successfully")
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
}
else
{
$("#status")
.addClass("error")
.html("An error occured, the data could not be saved")
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
}
}
});
}
Why does it don't seem to be working? Nothing have been send to my database, even I change to a simple alert, nothing appear
How can I improve it?
Probably because your HTML is invalid.
...
value="'.$row["Name"].' <--------- " is missing
onkeydown="if (eve...
<input type="text" id="your id" onkeypress="MAGIC(event);" />
function MAGIC(event){
$("#id").keyup(function(event){
if(event.keyCode == 13){
//your code to be executed
}
}

PHP & Java poll script displays same data multiple times after host has upgraded php to 5.4

I have been asked to fix a script on a webpage that has stopped working correctly since the webhost upgraded their supported version of php to 5.4, I have already tried downgrading the version via a htaccess file but without success.
The script basically uses a very simple database to store questions and log votes against them, it uses Java to actually display the questions and their answers and I think its this bit is causing the issues.
There are 5 questions in the database and the actual page itself shows the last question 5 times, which leads me to suspect that a variable is not being cleared somewhere.
Here are the scripts
$topPart = "";
$botPart = "";
$query = mysql_query("SELECT * FROM questions");
while ($row = mysql_fetch_assoc($query)) {
//display question
$topPart .= "pollNum=" . $row['id'] . ";\n";
$topPart .= "$('#loader'+pollNum).fadeIn();\n";
$topPart .= "$.get('poll.php', 'pollid='+pollNum, function(data, status){\n";
$topPart .= "loadpoll(data, status, '". $row['id'] ."')\n";
$topPart .= "});\n";
$botPart .= "<div id=\"pollcontainer" . $row['id'] . "\" class=\"question\" >". $topPart . "</div>\n";
$botPart .= "<p id='loader" . $row['id'] . "'>Loading...</p>";
I believe this bit is working ok since when examining the page the id's and classes are all numbered correctly, its the actual questions that repeat, the surrounding divs number correctly. This is the java... I know nothing about Java...
<script>
$(function(){
var pollNum;
<?php
echo $topPart;
?>
function loadpoll(data, status, pollNum){
//alert(pollNum);
var pollcontainer=$('#pollcontainer'+pollNum);
var loader=$('#loader'+pollNum);
pollcontainer.html(data);
animateResults(pollcontainer);
pollcontainer.find('#viewresult'+pollNum).click(function(){
//if user wants to see result
$('#formcontainer'+pollNum).fadeOut(100, function(){
loader.fadeIn();
$.get('poll.php', 'pollid='+pollNum+'&result=1', function(data,status){
loadpoll(data,status, pollNum);
});
});
//prevent default behavior
return false;
}).end()
pollcontainer.find('#viewvote'+pollNum).click(function(){
//if user wants to see result
$('#formcontainer'+pollNum).fadeOut(100, function(){
loader.fadeIn();
$.get('poll.php', 'pollid='+pollNum, function(data,status){
loadpoll(data,status, pollNum);
});
});
//prevent default behavior
return false;
}).end()
.find('#pollform'+pollNum).submit(function(){
var selected_val=$(this).find('input[name=poll]:checked').val();
if(selected_val!=''){
//post data only if a value is selected
loader.fadeIn();
$.post('poll.php', $(this).serialize(), function(data, status) {
$('#formcontainer'+pollNum).fadeOut(100, function(){
$(this).html(data);
animateResults(this);
loader.fadeOut();
});
});
}
//prevent form default behavior
return false;
});
loader.fadeOut();
}
function showresults(data, status, pollNum){
var pollcontainer=$('#pollcontainer'+pollNum);
var loader=$('#loader'+pollNum);
pollcontainer.fadeOut(1000, function(){
$(this).html(data);
animateResults(this);
pollcontainer.find('#viewvote'+pollNum).click(function(){
//if user wants to see result
loader.fadeIn();
$.get('poll.php', 'pollid'+pollNum, function(data,status){
pollcontainer.fadeOut(1000, function(){
$(this).html(data);
animateResults(pollcontainer);
});
loader.fadeOut();
});
//prevent default behavior
return false;
}).end()
});
loader.fadeOut();
}
function animateResults(data){
$(data).find('.bar').hide().end().fadeIn('slow', function(){
$(this).find('.bar').each(function(){
var bar_width=$(this).css('width');
$(this).css('width', '0').animate({ width: bar_width }, 1000);
});
});
}
});

Categories