Kevin Gr Zeballos
Kevin Gr Zeballos

Reputation: 33

How to show an alert box in php with differents responses?

Hi I'm super new in programing and I have to make an alert box showing my name or whatever I put on the URL.

my code to show my name on the screen is this one.

<?php   
echo "Hej $_GET[namn]"; 
?> 

and here is an example of what this does. http://www.webbacademy.se/webmaster/ovningar/php/get.php?namn=Kevin

which if I change the name on the url I get an alert with another name but I need to show it as an alert. but I have no ide how. this is what I've got so far but its not working.

<?php 

echo '<script language="javascript">';
echo 'alert("Hej $_GET[namn]")';
echo '</script>';


?>

Upvotes: 2

Views: 678

Answers (4)

YniA
YniA

Reputation: 11

I hope this will help.

<?php

$name = $_GET['namn'];
echo <<<s

 <script type="text/javascript">
    alert('$name');
 </script>

s;

?>

If you use <<<(some variable) after echo , you can write whaterver code you want as like your html without bothering about single or double quotes. But to use php variable values in your code you have to use '$var_name' like this.

Upvotes: 0

CodeGodie
CodeGodie

Reputation: 12132

The problem lies on this line: echo 'alert("Hej $_GET[namn]")';

Whatever is inside your '..'(quotes) will get printed as a string, thus you are seeing "Hej $_GET[namn]" as a result.

Also, you need to keep in mind theres a difference when using single quotes or double quotes. When using single quotes, you will need to concatenate any variables with the concatenation operator ('.'),(i.e. $string = 'I am '. $age .' years old.') however when you use double quotes you can just use your variable in your string (i.e. $string = "I am $age years old.").

What you need to do is first get the GET information then concatenate or use double quotes to include your variable in your string. I will use double quotes to make life easier:

$name = $_GET['namn'];
echo "<script> alert('Hej $name') </script>";

Hope this helps.

Upvotes: 1

Bob Dill
Bob Dill

Reputation: 1010

Create a string first, then echo the string...

$name = $_GET['namn'];
$outputString = "<script> alert('Hej $name') </script>";

echo $outputString;

Using the string approach will cause the contents of the "$name" variable to be placed in the string, which you can then echo to the browser.

Upvotes: 0

Domain
Domain

Reputation: 11808

alert() is a JavaScript function, so it will not work for PHP, however you can run a JavaScript code using PHP. After getting response from the server, it will execute in the browser.

This should work -

echo '<script type="text/javascript"> alert("Hej '.$_GET[namn].'"); </script>';

Upvotes: 0

Related Questions