How To Redirect With PHP
How To Redirect With PHP
How To Redirect With PHP
by Angela Bradley
Updated September 09, 2018
A PHP forwarding script is useful if you want to redirect one page to another so that your visitors
can reach a different page than the one they land on.
Fortunately, it's really easy to forward with PHP. With this method, you seamlessly transfer
visitors from the web page that no longer exists to the new page without requiring them to click a
link to continue.
On the page that you want to redirect elsewhere, change the PHP code to read like this:
The header() function sends a raw HTTP header. It must be called before any output is sent,
either by normal HTML tags, by PHP, or by blank lines.
Replace the URL in this sample code with the URL of the page where you want to redirect
visitors. Any page is supported, so you can transfer visitors to a different webpage on your own
site or to a different website entirely.
Because this includes the header() function, be sure that you do not have any text sent to the
browser before this code, or it will not work. Your safest bet is to remove all the content from the
page except for the redirect code.
If you remove one of your web pages, it's a good idea to set up a redirect so that anyone who
bookmarked that page is transferred automatically to an active, updated page on your website.
Without the PHP forward, visitors would remain on the dead, broken, or inactive page.
xxxxxxxxxxxxxxxxxxx
by Jennifer Kyrnin
Updated December 09, 2018
Novice website designers often want to know how to create a drop-down menu so that when
navigators choose one of the options they will automatically be redirected to that page. This task
isn't as tricky as it might seem. In order to set up a drop-down menu to redirect to a new Web
page when selected, you need to add some simple JavaScript to your form.
Getting Started
First, you need to set up your tags to include the URL as the value so that your form knows
where to send the customer. Once you've set up those tags, you will need to add an "onchange"
attribute to your tag to tell the browser what to do when the options list changes. Simply put the
JavaScript all on one line, which the example below shows:
onchange="window.location.href=
this.form.URL.options[this.form.URL.selectedIndex].value">
Helpful Tips
Now that your tags are set up, remember to make sure that your select tag is named "URL." If it
isn't, change the JavaScript above where ever it says "URL" to read your select tag's name. If you
want a more detailed example, you can see this form in action online. If you still need more
guidance, you can also review a brief tutorial that discusses this script and some other steps you
can take with JavaScript.
Under PHP you need to use header() to send a raw HTTP header. Using headers() method, you can
easily transferred to the new page without having to click a link to continue. This is also useful for search
engines. Remember that header() must be called before any actual output is sent, either by normal
HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or
require(), functions, or another file access function, and have spaces or empty lines that are output
before header() is called. The same problem exists when using a single PHP/HTML file.
<?php
/* Redirect browser */
header("Location: http://theos.in/");
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
The header() is used to send a raw HTTP/1.1 specification specific header. header() must be
called before any actual output is sent, the following example will not work:
<?php
$var="something";
echo "Hello world";
echo $var;
/****************************************************
* Remember that header() must be called before any actual output is sent,
* either by normal HTML tags, blank lines in a file, or from PHP.
*****************************************************/
header("Location: http://theos.in/");
exit;
?>
Create a sample function called movePage() in sitefunctions.php (note I’m not the author of the
following I found it somewhere else on the Internet):
function movePage($num,$url){
static $http = array (
100 => "HTTP/1.1 100 Continue",
101 => "HTTP/1.1 101 Switching Protocols",
200 => "HTTP/1.1 200 OK",
201 => "HTTP/1.1 201 Created",
202 => "HTTP/1.1 202 Accepted",
203 => "HTTP/1.1 203 Non-Authoritative Information",
204 => "HTTP/1.1 204 No Content",
205 => "HTTP/1.1 205 Reset Content",
206 => "HTTP/1.1 206 Partial Content",
300 => "HTTP/1.1 300 Multiple Choices",
301 => "HTTP/1.1 301 Moved Permanently",
302 => "HTTP/1.1 302 Found",
303 => "HTTP/1.1 303 See Other",
304 => "HTTP/1.1 304 Not Modified",
305 => "HTTP/1.1 305 Use Proxy",
307 => "HTTP/1.1 307 Temporary Redirect",
400 => "HTTP/1.1 400 Bad Request",
401 => "HTTP/1.1 401 Unauthorized",
402 => "HTTP/1.1 402 Payment Required",
403 => "HTTP/1.1 403 Forbidden",
404 => "HTTP/1.1 404 Not Found",
405 => "HTTP/1.1 405 Method Not Allowed",
406 => "HTTP/1.1 406 Not Acceptable",
407 => "HTTP/1.1 407 Proxy Authentication Required",
408 => "HTTP/1.1 408 Request Time-out",
409 => "HTTP/1.1 409 Conflict",
410 => "HTTP/1.1 410 Gone",
411 => "HTTP/1.1 411 Length Required",
412 => "HTTP/1.1 412 Precondition Failed",
413 => "HTTP/1.1 413 Request Entity Too Large",
414 => "HTTP/1.1 414 Request-URI Too Large",
415 => "HTTP/1.1 415 Unsupported Media Type",
416 => "HTTP/1.1 416 Requested range not satisfiable",
417 => "HTTP/1.1 417 Expectation Failed",
500 => "HTTP/1.1 500 Internal Server Error",
501 => "HTTP/1.1 501 Not Implemented",
502 => "HTTP/1.1 502 Bad Gateway",
503 => "HTTP/1.1 503 Service Unavailable",
504 => "HTTP/1.1 504 Gateway Time-out"
);
header($http[$num]);
header ("Location: $url");
}
}
<?php
@include("/path/to/sitefunctions.php");
If you are using Apple OS X or Linux/Unix-like operating system, open the Terminal app and
type curl command as follows:
$ curl -I your-url-here
$ curl -I www.cyberciti.biz/tips/
Sample outputs:
If you are on MS-Windows or do not want to use command line try redbot tool:
Fig.
01: Check HTTP Location url redirection with redbot tool
The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer
for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin,
Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.
Xxxxxxxxxxxxxxxx
There are certain times in life when you need a web page to do something more than just sit there
being a web page. You need it to earn its keep. One way to do that is to put it to work for you,
so you won't have to hand code every update or page mod. The easiest way to learn how to do
something like this is by actually doing it, so in the rest of this article, I'm going to show you one
way of implementing a system that will build new web pages for you at the touch of a button.
In this scenario, we'll assume your client is a restaurant that wants to offer vouchers for different
special occasions throughout the year. But of course they don't want to pay you to update it for
them, so you'd better make sure to bill them sufficiently for this automation system that will do
the updates for them
This is just a standard web page skeleton. You can give it a name like “pageBuilder.php” or
something. You don't have to use PHP for this. You could use another programming language,
but for this example we'll keep things simple and do it all in PHP.
2. Add Bootstrap
This will help to make the form look better without any extra work. Of course you'll need to
have Bootstrap for this to work.
3. Set up a container
To help keep everything neat and tidy, we should define a container that we'll store the page
contents in.
4. Create a web form
Define a web form, and we'll also add a fancy title to the form, which is optional but a good idea.
This is really simple. We just need to collect a few basic details that the robot will use to create a
new web page. The data we need to know includes:
The background image for the page
Name of the event being celebrated
Headline
Opening statement
Some trite quote or additional statement
Attribution for trite quote
Font style to use for each of the four framing text elements (individually).
Date range that the vouchers will be valid for
Offer 1 and Offer 2 that will be advertised on the vouchers.
Additional voucher messages (terms and conditions, for example)
Data for the voucher QR codes that will be generated
After creating a form, you need some software that will process the submitted data and do
something with it. In this case, we'll be using the submitted data to generate a new HTML page.
Now, keep in mind this is not the same thing as a normal PHP response where the data is used in
real time and reflected to the user dynamically. Instead, we are creating a static page that will
permanently exist until we overwrite it.
The file needs to be named the same as the action attribute value in the form declaration, so in
our example that would be voucherGen.php, and because we did not specify a path, it would
need to be stored in the same location as pageBuilder.php for it to work.
7. Initialize variables
The data submitted from pageBuilder.php was returned as an associative array called $_POST,
and all the data values in the array can be accessed via their HTML form control name
attributes. Therefore initializing our variables is actually quite easy. It's also optional, but it just
makes the code look a bit more tidy and easier to read. You could certainly work directly with
the $_POST values if you prefer.
Doing this early will save time and trouble later. We just check which values were selected and
then replace them with the actual font names.
9. Commence building the generator string
Really all we need to do here is create one really long string that will contain everything required
to create the new page. We will use string concatenation to keep it readable and make it easy to
see where the data values have been inserted. This starts with the basic HTML page set up:
You can probably see where we're going with this. Note the semi-colon at the end. That's
important. Also any semi-colons that occur within the text (as part of a CSS declaration or a
client-side script) must be contained inside quote marks.
10. Start adding the page body to the generator string
There are more efficient ways to build this string, but I like to make code tidy, so that it's easy to
read. You can use short hand methods to do this, and you also don't have to do it as a separate
process to step 9. I feel it's easier to understand when the different sections of the page are split
this way.
11. Write the generator string to a HTML
In this case we are hard-coding the file name, but you could (and probably should) make this a
field in your pageBuilder form.
When you click the BUILD IT button, because it doesn't redirect to a web page like a normal
PHP program would, you need to add a link or something to go and see what the result was.
You can store additional styling instructions in this file, but for now the only important one is the
styling instruction for the main div.
For this to work properly, you need to create a single translucent pixel image and name it
wrap.png then upload it to the path you specified in the custom.css file.
15. Upload some suitable background images and test your pageBuilder
You'll be thrilled to know we're almost done, and really it's now just a matter of testing and
fixing up any errors that occur. Choose some nice simple images that are not too busy and that
are suitable to relate to special events or occasions (in our example, I've gone with Mother's Day
and Father's Day). Upload the images to the path where you store your images for your website.
Then fill in the form, click the button, and see what happens. Here's an example of the form with
all the data fields filled in.
Which should result in creating something quite similar to this:
We already guessed you wouldn't want to type all that from scratch, so you can download the
source code for pageBuilder.php and voucherGen.php in this zip file.
You can apply this technique of creating HTML files as strings and then writing them out to files
in all kinds of situations. Just be careful never to put something like this in a recursive loop or
you'll fill up your hard drive and crash the server.
262 shares
Tweet Share on Facebook Submit to reddit Add to buffer Save to pocket Email
Get the most complete ebook on how to grow your online shop. 100+ pages of amazing advice and
insights!
I'm a web design blogger and started this project after spending a few weeks struggling to find
out which is the best ecommerce platform for myself. Check out my current top 10 ecommerce
site builders.
Xxxxxxxxxxxxxxxxxxxxxxxxxx
Neeraj Agarwal
To retrieve or fetch data from MySQL database it is simple to do it using MySQL ” Select
” query in PHP .
Here in this blog post we will be going to see how to fetch data and to display it in front end.
SELECT column_name(s)
FROM table_name
PHP:
For this you must have a database in MySQL . Here, we have a database named “company”
which consists of a table named “employee” with 5 fields in it.
Next we have created a PHP page named “updatephp.php” where following steps will be going
to perform:
Selects database.
mysql_close($connection);
Below is our complete code with download and live demo option
Download script
PHP File: readphp.php
<!DOCTYPE html>
<html>
<head>
<title>Read Data From Database Using PHP - Demo Preview</title>
<meta content="noindex, nofollow" name="robots">
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="maindiv">
<div class="divA">
<div class="title">
<h2>Read Data Using PHP</h2>
</div>
<div class="divB">
<div class="divD">
<p>Click On Menu</p>
<?php
$connection = mysql_connect("localhost", "root", ""); // Establishing
Connection with Server
$db = mysql_select_db("company", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from employee", $connection);
while ($row = mysql_fetch_array($query)) {
echo "<b><a
href="readphp.php?id={$row['employee_id']}">{$row['employee_name']}</a></b>";
echo "<br />";
}
?>
</div>
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query1 = mysql_query("select * from employee where employee_id=$id",
$connection);
while ($row1 = mysql_fetch_array($query1)) {
?>
<div class="form">
<h2>---Details---</h2>
<!-- Displaying Data Read From Database -->
<span>Name:</span> <?php echo $row1['employee_name']; ?>
<span>E-mail:</span> <?php echo $row1['employee_email']; ?>
<span>Contact No:</span> <?php echo $row1['employee_contact']; ?>
<span>Address:</span> <?php echo $row1['employee_address']; ?>
</div>
<?php
}
}
?>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
</div>
<?php
mysql_close($connection); // Closing Connection with Server
?>
</body>
</html>
MySQL Code Segment: Here is the MySQL code for creating database and table.
@import "http://fonts.googleapis.com/css?family=Droid+Serif";
/* Above line is to import google font style */
.maindiv {
margin:0 auto;
width:980px;
height:500px;
background:#fff;
padding-top:20px;
font-size:14px;
font-family:'Droid Serif',serif
}
.title {
width:100%;
height:70px;
text-shadow:2px 2px 2px #cfcfcf;
font-size:16px;
text-align:center;
font-family:'Droid Serif',serif
}
.divA {
width:70%;
float:left;
margin-top:30px
}
.form {
width:400px;
float:left;
background-color:#fff;
font-family:'Droid Serif',serif;
padding-left:30px
}
.divB {
width:100%;
height:100%;
background-color:#fff;
border:dashed 1px #999
}
.divD {
width:200px;
height:480px;
padding:0 20px;
float:left;
background-color:#f0f8ff;
border-right:dashed 1px #999
}
p {
text-align:center;
font-weight:700;
color:#5678C0;
font-size:18px;
text-shadow:2px 2px 2px #cfcfcf
}
.form h2 {
text-align:center;
text-shadow:2px 2px 2px #cfcfcf
}
a {
text-decoration:none;
font-size:16px;
margin:2px 0 0 30px;
padding:3px;
color:#1F8DD6
}
a:hover {
text-shadow:2px 2px 2px #cfcfcf;
font-size:18px
}
.clear {
clear:both
}
span {
font-weight:700
}
Conclusion:
We have shown you how SELECT command of SQL is executed with PHP, for fetching data
from database. For more MySQL commands with PHP, follow our other blog posts .
Xxxxxxxxxxxxxxxxxxxxxxxx
The SELECT statement is used to select data from one or more tables:
The following example selects the id, firstname and lastname columns from the MyGuests table
and displays it on the page:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
First, we set up an SQL query that selects the id, firstname and lastname columns from the
MyGuests table. The next line of code runs the query and puts the resulting data into a variable
called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into an
associative array that we can loop through. The while() loop loops through the result set and
outputs the data from the id, firstname and lastname columns.
The following example shows the same as the example above, in the MySQLi procedural way:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".$row["lastname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
It selects the id, firstname and lastname columns from the MyGuests table and displays it in an
HTML table:
Example (PDO)
<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";
function current() {
return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();
Xxxxxxxxxxxxxxxxx
A prepared statement is a feature used to execute the same (or similar) SQL statements
repeatedly with high efficiency.
1. Prepare: An SQL statement template is created and sent to the database. Certain values are left
unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?)
2. The database parses, compiles, and performs query optimization on the SQL statement
template, and stores the result without executing it
3. Execute: At a later time, the application binds the values to the parameters, and the database
executes the statement. The application may execute the statement as many times as it wants
with different values
Compared to executing SQL statements directly, prepared statements have three main
advantages:
Prepared statements reduce parsing time as the preparation on the query is done only once
(although the statement is executed multiple times)
Bound parameters minimize bandwidth to the server as you need send only the parameters
each time, and not the whole query
Prepared statements are very useful against SQL injections, because parameter values, which
are transmitted later using a different protocol, need not be correctly escaped. If the original
statement template is not derived from external input, SQL injection cannot occur.
The following example uses prepared statements and bound parameters in MySQLi:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$firstname = "Mary";
$lastname = "Moe";
$email = "[email protected]";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "[email protected]";
$stmt->execute();
$stmt->close();
$conn->close();
?>
In our SQL, we insert a question mark (?) where we want to substitute in an integer, string,
double or blob value.
This function binds the parameters to the SQL query and tells the database what the parameters
are. The "sss" argument lists the types of data that the parameters are. The s character tells mysql
that the parameter is a string.
i - integer
d - double
s - string
b - BLOB
Note: If we want to insert any data from external sources (like user input), it is very important
that the data is sanitized and validated.
The following example uses prepared statements and bound parameters in PDO:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "[email protected]";
$stmt->execute();
xxxxxxxxxxxxxx
How TO - Popup
Example
Example
/* Popup container */
.popup {
position: relative;
display: inline-block;
cursor: pointer;
}
/* Popup arrow */
.popup .popuptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
/* Toggle this class when clicking on the popup container (hide and show the popup) */
.popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s
}
@keyframes fadeIn {
from {opacity: 0;}
to {opacity:1 ;}
}
Example
<script>
// When the user clicks on <div>, open the popup
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
</script>
JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box
An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
window.alert("sometext");
Example
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
Syntax
window.confirm("sometext");
Example
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after
entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns
null.
Syntax
window.prompt("sometext","defaultText");
Example
Line Breaks
To display line breaks inside a popup box, use a back-slash followed by the character n.
Example
xxxxxxxxxxxxx
1. <?
2. if(! valid username or password)
3. {
4. echo '<script language="javascript">alert("Please enter valid username
and password");</script>';
5. header("Location:currentpage.php");
6. exit;
7. }
8. else
9. {
10. //--- continue.....
11. }
12. ?>
Because of it's powerful flexibility, I prefer PHP for my popups. Well... they may not
ACTUALLY be popups. But functionally they are the same if you don't really require a
complete browser window.
The easiest and my preferred method is simply to hide a <div> with the popup content inside of
an "if {" statement. If you format the <div> with a class in your stylesheet similar to this:
1. div.popup {
2. position: absolute;
3. left: 100px;
4. top: 100px;
5. width: (some width);
6. height: (some height);
7. z-index: 1;
8. }
The key is the z-index which places the <div> above the other content. The <div> will only
appear when the 'if' condition is met. This is very powerful when used in conjuction with mysql.
You can come up with all kinds of conditions. 'if the user is visiting for the first time', if the user
hasn't visited your site for awhile', 'if the user just placed an order'. etc, etc. The possibilities are
endless.
Another option would be to pass information through a link with $_GET. It could simply be a
link to the same page the user is viewing. You can format it however you like. The important
part is just to get the php info across.
1. a href="http://PageYouAreViewing?popup=SomePopup"
Then you could use $_GET the info to achieve the popup result:
1. if (isset($_GET['popup']))
You could use the $_GET info to meet an 'if' condition that opens a popup <div> or even
multiple <div>'s.
Add in a switch for multiple popup options. And you have more options than you know what to
do with.
1. $popup = ($_GET['popup']);
2.
3. switch($popup){
4.
5. case SomePopup:
6. conditions for popups;
7. break;
8. case AnotherPopup:
9. another condition for popups;
10. break;
11. case AnotherPopup:
12. another condition for popups;
13. break;
14. }
While these aren't actual windows, they are GREAT for interaction with a web site user, you
won't need to worry about a pop-up blocker and users usually prefer less windows cluttering up
their desktop anyway. If you store info to mysql (logs, customers, orders, users, etc) you can
come up with all sorts of conditions.
xxxxxxxxxxxxxxx
In this article I explain how to use various types of popup boxes in PHP.
Sharad Gupta
Jun 21 2013
1
1
119.2k
facebook
twitter
linkedIn
google Plus
Reddit
o Email
o Bookmark
o Print
o Other Artcile
Expand
In this article I explain how to use various types of popup boxes in PHP. If you learn JavaScript then you
know that JavaScript has the following three types of popup boxes:
Alert box
Confirm box
Prompt box
Now here I explain all these popup boxes with PHP one by one.
Alert Box
An alert box is used if you ensure the information comes through the user. It means an alert box pop-up,
when you click on a "button".
Syntax
Example
<?php
</script>';
?>
Output
Confirm Box
A confirm box is used when you want the user to verify or accept something.
Syntax
Example
if the user clicks "ok" then the confirm box returns true and is the user clicks "Cancel", then the box
returns false.
<html>
<head>
<script>
function myFunction() {
var x;
else {
document.getElementById("demo").innerHTML = x;
</script>
</head>
<body>
<?php
?>
<p id="demo"></p>
</body>
</html>
Output
A prompt box is used when you want the user to input a value before entering a page and when a prompt
box pops up, the user will need to click either "OK" or "Cancel" to proceed after entering an input value.
Syntax
Example
<html>
<head>
<script>
function myFunction() {
var x;
if (site != null) {
document.getElementById("demo").innerHTML = x;
</script>
</head>
<body>
<?php
?>
</body>
</html>
Output
Example
The alert() method displays an alert box with a specified message and an OK button.
An alert box is often used if you want to make sure information comes through to the user.
Note: The alert box takes the focus away from the current window, and forces the browser to
read the message. Do not overuse this method, as it prevents the user from accessing other parts
of the page until the box is closed.
Browser Support
Method
Syntax
alert(message)
Parameter Values
Parameter Type Description
Technical Details
Return Value: No return value
More Examples
Example
Example
alert(location.hostname);
Related Pages