Counting Number of attemps left using ajax - java

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.

Related

how can we apply validation in a jsp page

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.

redirect user to login page

I'm running a J2EE application and need to redirect the user to login page if the session is inactive.
I basically want to use the below javascript code to get the session last accessed time and compare with the current time, and if its more than the session timeout I will logout:-
<script>
setInterval(function() {
console.log('MaxInactive Interval == ' + <%=new Date(session.getLastAccessedTime())%> );
}, 10000);
</script>
I get the below error on the console.log line:-
Uncaught SyntaxError: missing ) after argument list
Here is the display from the sources tab:-
console.log('MaxInactive Interval == ' + Sun May 31 20:33:17 EDT 2015 );
You should place the single quote at the end of console.log argument
setInterval(function() {
console.log('MaxInactive Interval == <%=new Date(session.getLastAccessedTime())%>' );
}, 10000);
</script>
And you don't need the + operator, you cannot concatenate javascript string with java expressions.

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.

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