SetTimeOut on Alert Box - javascript

Thanks for every bit of help that you have all rendered in this forum.
On behalf of others, I am grateful and want to make you understand that.
Meanwhile, there is this quest that I need to get solved.
Setting a timeout on an alert box.
That is,
<?php
echo '
<script type="text/javascript">
var t = setTimeOut(5000); //5secs
alert("Your score is: ". $score. '.");
if(t === TRUE){
//clear alert box
this.alert.OK = true;
window.location = "index.php";
}
</script> ';
?>
Please do not mind my psudo-code. It's just my wrongest way of understanding javascript to work.
I know that everything is possible - there could be some way of getting around a challenge. But I do not really have the actual solution. And I am throwing it open to the gurus in the house.
Thanks in anticipation that we will all get through this challenge together.
I remain your loyal friend.

You can't time out an alert. It's a low-level JavaScript construct that creates a native application dialog that needs to be confirmed by the user before it gets destroyed. If you want to "throw up data" to the user, you'll have to use an actual HTML dialog library (or roll your own).
Also, don't use alert(). It was great when we had no alternative, but these days you use console.log(...) to simply log data (any data. numbers and strings, but also entire objects and HTML elements!) to the dev tools console (every browser comes with one baked in), and there are a million and one JS libraries that will generate nice looking modals for users instead (the only legitimate use of an alert these days is to force a halt on the entire page processing thread... And off the top of my head I can't think of a single reason why you'd want to do that).
That said, the PHP code you gave makes absolute no sense at all. It's literally a .js file, with a .php extension. Remove those php tags, save it as .js, and just <script src="thatfile.js"></script> that thing. Don't make PHP do things that you don't need PHP for in the slightest.

Browsers won't allow timeout on their alert, at-least as of now it is not possible. But here is possible way around. Create a message box with html and css.
php:
<?
... what required to compute/fetch the score
?>
<html>
<head>
<meta http-equiv="refresh" content="5;index.php"/><!-- redirect after 5 secs -->
</head>
<body>
<div class="message-box">
<label>Your score is:<?$score?></label>
</div>
</body>
</html>
The meta tag will tell the browser to redirect to the given page after 5 seconds. Mean while the page is displayed to the user with dynamic score given by the php variable.
EDIT: In case if you are not allowed to use meta tags then try this
<?
... what required to compute/fetch the score
?>
<html>
<body>
<div class="message-box">
<label>Your score is:<?$score?></label>
</div>
</body>
<!-- not a good practice to put tag here, but it will do the trick to redirect after page is loaded-->
<script>
setTimeout(function(){
location.assign("index.php");//<-- where to redirect
}, 5000); //<-- redirect after 5 secs
</script>
</html>

is it not possible to do:
var t = setTimeOut(function(){
alert("Your score is: ". $score. '.");
},5000); //5secs
?

Related

How can I get a data from one html form and display it on another?

I'm using only JS and I want to get a username from one html and display it on the another html page. I'm a beginner on the programming and I have two questions:
Can I use only one JS file to do this? If yes, how?
Why it isn't working?
First page
<main>
<form action="">
<input type="text" name="login" id="login" class="login" placeholder="Login">
<a href="password.html" id='logar'>LOGAR!</a>
</form>
<span id='spanlogin'></span>
</main>
<script src="main.js"></script>
var login = document.getElementById('login').value;
localStorage.setItem("thelogin", login);
Second Page
<main>
<div>
<span id='showlogin'></span>
</div>
<div class="senha">
</div>
</main>
<script src="second.js"></script>
var ologin = localStorage.getItem('thelogin');
function showthelogin(){
document.getElementById('showlogin').innerHTML = ologin
}
window.onload = showthelogin()
Thanks for the help!
For what it's worth, the login button is just a link, it's not running the js on the first page. The js executes immediately on page load when the form is still empty. If you wrap it in a function and call the function on click, it will do what you want.
What you want, might not be what you need, but getting things to do what we want them to do can help us better understand what we need.
main.js
function savePassword(){
var login = document.getElementById('login').value;
localStorage.setItem("thelogin", login);
}
first page:
LOGAR!
In answer to your first question, you can do it with just one page. For example, read about Single-page applications.
Note that the way you're doing it is not the same thing as 'submitting' the form.
"For documents loaded from file: URLs (that is, files opened in the browser directly from the user’s local filesystem, rather than being served from a web server) the requirements for localStorage behavior are undefined and may vary among different browsers.
In all current browsers, localStorage seems to return a different object for each file: URL. In other words, each file: URL seems to have its own unique local-storage area. But there are no guarantees about that behavior, so you shouldn’t rely on it because, as mentioned above, the requirements for file: URLs remains undefined."
Its from developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Append input field value to url on button click

I'm very new to coding, so please forgive me if this is a dumb question.
I'm working on an assignment where I have to add functionality and styles to an existing bootstrap HTML doc. The purpose is to allow people to enter a dollar amount into an input field either by typing in an amount or by clicking buttons that populate the field with set amounts. One of my instructions was to update the donate submit button so that it appends the chosen donation amount to the "/thank-you" URL.
This is what I have for the input field:
<form id="amountSend">
<input type="text" class="form-control donation-amount-input" placeholder="Other" id="other-amount"/>
</form>
This is what I have for the button:
<button id="donateBtn" type="submit" action="/thank-you"
method="get">DONATE<span class="metric-amount"></span></button>
And I was thinking that the jQuery would look something like this, though the submit function is not currently giving me any visible results.
$("#donateBtn").click(function() {
if (!$.isNumeric($("#other-amount").val())) {
$("#dataWarning").show();
$(".metric-amount").hide();
$(".metric-message").hide();
} else {
$("#amountSend").submit(function() {
var url = "/thank-you";
$(".metric-amount").appendTo("url");
});
}
})
I also got some decent results using a PHP method:
<form id="amountSend" method="post" action="/thank-you.php">
<input type="text" class="form-control donation-amount-input" placeholder="Other" id="other-amount" name="donation"></input>
</form>
<button id="donateBtn" type="submit">DONATE<span class="metric-amount"></span></button>
<script>
$("#donateBtn").click(function() {
if (!$.isNumeric($("#other-amount").val())) {
$("#dataWarning").show();
$(".metric-amount").hide();
$(".metric-message").hide();
} else {
$("#amountSend").submit();
}
});
</script>
This one will open the PHP file I set up (/thank-you.php, which i have stored just in the same root folder as my main HTML doc), but all the browser gives me is the raw HTML code of the PHP file. Here's the code I have in the PHP file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
Thank you for your donation of
<?php echo $_POST["donation"]; ?><br>
</body>
</html>
Anyway, I guess I'm wondering if I'm on the right track? Should I pursue the jQuery or PHP method? Can I even do this using only jQuery? I've seen a few posts on this subject already, but I thought I'd make a new one since the ones I've seen are all fairly vague, I haven't seen the same answer twice, and I'm not sure I fully understand exactly what I'm trying to accomplish, in terms of a visual confirmation of results.
Thanks!
First of all, you have several issues with your code.
Number one: The formulary you have there is bad coded, the form tag needs to have the action and method attributes, not the submit button.
And in top of that, the submit button needs to be inside the form tag, if is not in there, it will not have and kind of effect.
Number two: If you are gonna submit the formulary to a php file and handle the request there ,you need the file to be running on a server (local or whatever). PHP is a server language, if you open the file directly in a browser, it will show you the code it has inside and will not work.
Hope it helps!

Can I force a page in history to be removed?

Re editing... this question has NOT been answered before!
I had understood that changing the contents of a current page with window.location replaced the cached version of the original page ( from the "last" history), so that you really couldn't go back with the browser BACK button. I had even seen this posted as a solution to preventing a malicious visitor from using the BACK button to to re-submit a mail form many times. But it is NOT workable because in the case of a mail form, the BACK button will just take the user back to the pre-POST version of the page.
So, I can use javascript to reset the form, disable the SUBMIT button, change to another page after success, or do whatever I want to the page. But its all for nothing if a simple click of the BACK button followed by SUBMIT causes the form to post again with just 2 clicks.
I know there are a lot of solutions to preventing malicious form resubmissions I can try, but I've had trouble getting them to work, and so I'd just like to know if removing the last history is a dead end. If there is a way, and it is pretty cross browser friendly, then I can just make it part of my scripted actions once my form is successfully processed, and my "thank you" page displays. Basically I'd want my "thank you" page's 'onload' event to either erase the last history, or in a browser compatible way disable the BACK button!
For what its worth, I've included code from simple test I've been working with. You can put some junk in the fields and hit submit. The vars are cleared in the PHP, the form fields are force cleared in javascript, and a new 'location' is invoked. Unfortunately, hitting BACK button will take you back to the "pre-posted" form, with all the strings you added still intact.
<!DOCTYPE HTML>
<html>
<head>
<title> Form Behavior Test</title>
</head>
<!--
<?php
$name = $email = $comments = "";
$formDone = false;
if ($_SERVER["REQUEST_METHOD"] == "POST" )
{
$formDone = true;
$name = $email = $comments = "";
}
?>
-->
<body >
<table border="1"><tr><td style ="text-align:right;" width=100%>
<form name="contactform" id="contactform" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" id="name" value="<?php echo $name;?>"><br>
Email: <input type="text" name="email" id="email"value="<?php echo $email;?>"><br>
<br>
<div align="center"> ---- <span class="error">*</span> Message ---- <br>
<textarea name="comments" id="comments" wrap="physical" cols="40" rows="10" ><?php echo $comments;?></textarea>
</div>
<input name="submit" id="submit" type="submit" value="Submit" >
</form>
</td></tr></table>
<script language="JavaScript">
if (<? echo ($formDone == true) ? 'true' : 'false'; ?>)
{
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementById("comments").value = "";
document.getElementById("submit").value="Disabled";
document.getElementById("submit").disabled=true;
// substitute with a thank you page
window.location = "http://google.com";
}
</script>
</body>
</html>
After searching pretty exhaustively, I don't believe there is any way to remove a page from history, except on the very latest browsers that support newer HTML-5 history methods. I'm still open to solutions but at this point I think the easiest thing will be for me to set a cookie anytime a successful email is processed by my PHP code. Then, I can also make the PHP or a javascript snippet look for the cookie and if found, I can take all kinds of actions... wipe out all filled in fields (as they would be if the BACK button is pressed), block the email, politely inform the user that he/she must wait (until my cookie expires) to send another email though the form, etc.
I didn't want to do this originally because the BACK button doesn't actually re-load the page, it just displays it. If there were a universal browser compatible way to make pages reached by back buttons actually re-load, this would never have been a problem to begin with. So even with a cookie, my defensive actions couldn't activate until the SUBMIT button is pushed. I guess I can live with that. Also, even today, some people are paranoid about cookies and turn them off. But if I want to be adamant about it, I can just detect when I can't set a cookie, and inform the user that cookies are required to use my email form. If that's too big a deal, oh well!
Thanks to those that contributed. The fact is, the LACK of answers is really a very useful answer sometimes. When I post on any stackoverflow forum and don't get any answers pretty quickly, its a good red-flag that things are going to get convoluted really fast if I don't consider an alternate approach! :-)

Get php variable from url on reload without refresh

I'm working on a hobby project (usually working as a designer, so not all that familiar to php – please have oversight with all or any redundant code), trying to learn new things. Now I've bumped into a problem that I don't quite seem to get the hang of.
I have an index.php used to display random sentences from data.php, this works fine – however I want to be able to sort out specific types of sentences for different people if necessary. This is done with a dropdown containing Designer, Illustrator and Developer.
If for example you choose Developer from the dropdown menu, the page reloads with index.php?yrke=developer in the URL as a result. This is all fine and as expected, and when i echo $_GET['yrke']; from data.php it displays the text "developer" fine the first load, but upon clicking the randomizerButton button (note that the content is loaded from data.php without refreshing the page in the browser when clicking this button) $_GET['yrke']; does not seem to be able to get a read on the value in the url (putting $_GET['yrke']; in index.php obviously works regardless, but I need to access the url variable in data.php).
If there's a way to do this while maintaining the "update-content-without-browser-refresh" function that'd be awesome, the other easiest solution would perhaps be to remove said "update-content-without-browser-refresh" and go for good old refreshes and thus solving the problem – but why make it that easy right?
index.php (excerpt)
<button data-href="data.php" class="randomizerButton">Randomize sentences</button>
<form action="index.php" method="get">
<select name="yrke" onchange="this.form.submit()">
<option value="designer"<?=$_GET['yrke'] == 'designer' ? ' selected="selected"' : '';?>>Designer</option>
<option value="illustrator"<?=$_GET['yrke'] == 'illustrator' ? ' selected="selected"' : '';?>>Illustrator</option>
<option value="developer"<?=$_GET['yrke'] == 'developer' ? ' selected="selected"' : '';?>>Developer</option>
</select>
</form>
<?php include('data.php'); ?>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('button.randomizerButton').click(function(){
scriptUrl = $(this).attr('data-href');
$.post(scriptUrl, function(response){
$('#results').html(response);
});
});
});
</script>
data.php (excerpt)
echo $_GET['yrke'];
If you want $_GET['yrke'] on data.php you would have to use $.get() and just use the full URL, like:
$.get('data.php?yrke='+encodeURIComponent($('[name=yrke]').val()), function(response){
$('#results').html(response);
}
I would use
$.post('data.php', {yrke:encodeURIComponent($('[name=yrke]').val())}, function(response){
$('#results').html(response);
}
with $_POST['yrke'] on data.php. Usually, I would not have a form that submits in the traditional manner. It's all about the AJAX.
Not sure if this will help but you could do something like this...
<div id ="content">
<?php
$pages_dir ='pages';
if(!empty($_GET['p'])){
$pages =scandir($pages_dir, 0);
unset($pages[0], $pages[1]);
$p = $_GET['p'];
if (in_array($p.'.inc.php', $pages)){
include($pages_dir.'/'.$p.'.inc.php');
}else {
echo'Page not found';
}
}else{
include($pages_dir.'/home.inc.php');
}
?>
HERE
</div>
Make a folder called pages then name the files within the folder "aboutus.inc.php" ect. the important part of the file extension is .inc.php , you can name anything before .inc.php anthing you like here is an example of how to write the navigation "About us"
IF need be I can send you a blank template

Using PHP to get the value of input type range onchange

I am trying to get the value of a range slider after it moves and then update my page. I have approached this by using "onchange" and calling some javascript to set a value to a text box and using php to get that value. The php does not even grab the value from the text area on load and I am not sure why. It says the id of the input text box is an "unidentified index." There might be a simple thing wrong or I may be approaching it completely wrong. I am new to this...
Here is the code for the slider.
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<script>
function printValue(sliderID, textbox) {
var x = document.getElementById(textbox);
var y = document.getElementById(sliderID);
x.value = y.value;
}
window.onload = function() { printValue('slider1', 'rangeValue1')};
</script>
</head>
<body>
<form action='slider.php' method='get'>
<input id="slider1" type="range" min="100" max="500" step="10" onchange="printValue('slider1','rangeValue1')">
<input id="rangeValue1" type="text" size="2">
</form>
<?php
echo $_GET['#rangeValue1'];
?>
</body>
</html>
The js function does set input text box, but the php script doesn't happen. I need to get the value in PHP because the page I'm including it in is written in PHP. I don't know if, or how, the page has to be reloaded. I tried using location.reload() in the onchange function and it just continuously loaded the page.. Please help! Any input will be helpful! Thanks!
It looks like you might be getting Javascript and PHP mixed up.
PHP is run solely on your server when a browser accesses a php file. The output of the php file (like when you use echo) is sent as a webpage. However, Javascript is run solely in the browser. To make them communicate, you will need to load another webpage (or reload the current webpage). You can either use a form or directly craft the URL (probably easier in this case).
So you could do something like this inside printValue():
location.querystring="?value=" + x.value;
This will create a GET argument, which you can access with $_GET['value'], and reload the page.
EDIT: Performance Warning!
Every time the slider is moved, your server will end up resending the webpage, which could slow down the server. You might want to only send the new value after the user has clicked a button or something, in which case it would be easier to use a form.

Categories

Resources