Creating a javascript alert with php that has a php variable inside? - javascript

I'm making a form that is supposed to create a javascript alert when some fields aren't filled out or filled out properly. I want to be able to take the error messages I've put in a php variable and display them in the javascript alert window.
The following code does not work:
function died($error) {
echo '<script type="text/javascript"> alert('.$error.')</script>';
die();
}
How can I add the string contained in $error between the two "script" strings so it will output properly as a javascript alert?
Thank you!

You only forgot quotations that are required for the JavaScript alert.
If you passed 'hello' to the function, your current code would create alert as:
alert(hello)
instead of doing:
alert("hello")
Therefore, change your line to the following (two double quotes are added before and after concatenating $error):
echo '<script type="text/javascript">alert("'.$error.'");</script>';
and you can use your function:
died('error on whatever');

Display variable php in alert javascript
<?php
function died($error) { ?>
<script>alert("<?php echo $error; ?>")</script>
<?php die();
} ?>

You can use function follow this:
function died($error) {
echo '<script> alert("'.$error.'")</script>';
die();
}

<?php
echo "<script type='text/javascript'>alert('{$_SESSION["success"]}');</script>";
unset($_SESSION["success"]);
?>
Use this code it would work correctly

Related

PHP Pass Variable to new Window.Open Javascript

I have read the following posts, but they are a little over the top for me. I think I'm trying to do something fairly simple, and would like some guidance.
How to pass variables and data from PHP to JavaScript?
passing PHP variables across javascript windows.open to another PHP page
Posting a php variable to a new window
Here is the case:
I have a php script which is very simple, it calls another script and passes 2 variables:
<?php
echo '<script type="text/javascript" language="javascript">
window.open("http://callpage.com/utils/cdr.php?callernum=123456789&calltime=2017-02-22 16:24:12");
</script>';
?>
Note: This is just a "hardcoded" example.
The next script, takes those numbers and builds file/url variable.
Lets say
$file = /var/www/html/file.wav
What I'm trying to do open a new window to the effect of :
http://newpage.com/$file
I have read and found that I think the best use is Javascript, but I can't seem to get my variable into the Javascript.
Here is what I would like to get working:
<?php
$file = /var/www/html/file.wav
echo '<script type="text/javascript" language="javascript">
window.open("http://newpage.com/$file");
</script>';
?>
A few notes:
I don't want to "redirect" the old page, I want it to stay open, and the remote page isn't on the same domain
(one is a.domain.com and the other is b.domain.com).
I don't care about window sizes, etc, its a wav file that I'm expecting the browser to just play with a simple Browser default interface for Wav.
if I understood correctly what you want, you have to concatenate the string with the variable in order to be replaceed
<?php
$file = '/var/www/html/file.wav';
echo '<script type="text/javascript" language="javascript">
window.open("http://newpage.com/'.$file.'");
</script>';
?>
Use string interpolation with double quotes for the echo statement and single quotes everywhere inside the javascript:
echo "<script type='text/javascript' language='javascript'>
window.open('http://newpage.com/$file');
</script>";
The interpolated PHP variable $file should be correctly interpreted as a string and the value it holds should be displayed in the URI of your javascript.
Check out this easy to understand info about variable interpolation http://phppot.com/php/variable-interpolation-in-php/
Here is my "final" code snippet:
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$uid = $row['uniqueid'];
foreach(glob($path. "*". $uid. "*") as $file) {
$link = "http://newpage.com$file";
echo "<script type='text/javascript' language='javascript'>
window.open('$link');
</script>";
}
}

concatening PHP variable and strings inside double quotes for onclick event

The button when pressed call a function that needs the sn value, but the code below fails with the Chrome debug message:
Uncaught ReferenceError: Telephony is not defined
Telephony is one of the service names.
<html>
<head>
<title>someTitle</title>
<script>
function myF(varname) {
//I'll do here some other task with varname
console.log(varname);
}
</script>
</head>
<body>
<pre>
<?php
$sn='noname';
//here, the code to connect and select DB
while ($reg=mysql_fetch_array($registers))
{
echo "Service Name: ".$reg['sname']."<br>";
$sn = $reg['sname'];
echo "<button onclick=\"myF($sn)\">Vote</button>";
echo "<hr>";
}
mysql_close($conexion);
?>
</pre>
</body>
</html>
Is it possible a simple solution? My PHP server has PHP5
Assume your variable $sn is "Stack". Hence $sn is a string you need to pass this variable
as a string.
So rewrite myF($sn) as myF("'".$sn."'").
When yu inspect the button you can see myF('Stack').
then in javascript you can avoid the error.
Why do you need double quotes?
echo "<button onclick=\"myF($sn)\">Vote</button>";
Do this instead:
echo '<button onclick="myF(\''. $sn . '\')">Vote</button>';
Or perhaps do it with sprintf like this:
echo sprintf("<button onclick=\"myF('%s')\">Vote</button>", $sn);
Does this work?
echo "<button onclick=\"myF('$sn')\">Vote</button>";
I tried out a simple test case, without any MySQL. You can find the code I used below:
<?php
$sn='noname';
$registers = array(array('sname' => 'apple'), array('sname' => 'banana'), array('sname' => 'woodapple')); // Dummy "MySQL" Fetch Array (this might differ from what your 'while' loop receives)
foreach ($registers as $reg){ // In your case, a 'while' loop works.
echo "Service Name: ".$reg['sname']."<br>";
$sn = $reg['sname'];
echo "<button onclick=\"myF('$sn')\">Vote</button>"; // Added Quotes.
echo "<hr>";
}
?>
HINT: Please refrain from using mysql_* functions! They are deprecated!
Your concatenation need to change like this,
echo '<button onclick="myF("'.$sn.'")">Vote</button>';
I think that when you are passing the PHP variable as an argument in to the onclick event of button for calling javascript function, you string breaks because it is not quoted. So it needs to be quoted. I have edited the code line where you need to edit you code. So try like:
...
......
........
........
echo "<button onclick=\"myF("$sn")\">Vote</button>";
.......
......
....

PHP function return value to JavaScript

I need to send result from my PHP file to the JavaScript function/file.
I found some of answers like: var x='<?php echo $pathinfo; ?>';
or this:
myHtmlFile.html:
<script type="text/javascript" src="jquery-1.8.1.js"></script>
<script type="text/javascript" src="newEmptyPHP.php"></script>
<script language="javascript">
function test()
{
alert(result);
}
</script>
newEmptyPHP.php:
<?php
$res="it is result";
echo "var result = ".json_encode($res).";";
?>
My question is whether there is way return value from php function and not from php file.
something like this:
<?php
function phpFunction(){
$res="it is result";
return $res;
}
?>
I need simple PHP/JavaScript code without something complex.
I want keep many function in one php file and not many php files.
<?php
function phpFunction(){
$res="it is result";
return $res;
}
?>
<script>
var result = "<?php echo phpFunction() ?>";
</script>
The above method will work. However, if you want more PHP/JS combined scripts, learn AJAX.
The best way to get your data to JavaScript from PHP is to use AJAX using jQuery you have declared.
You can use $.get()
You can call you php script which contains the function with parameters in you url request.
And when a specific parameter is specified in the url, then you can call you fonction and echo whatever you want to the javascript.
Have a good day!
You can open as many php tags as you wish inside your one php document. You can then either make this php document separate from your main document (however this would require making the main document in php and using a "php include" or "php require") or you can simply just open and close php tags as necessary. You do not even have to close the line at the end of the php, for example.
<?php if (a==a) { ?>
<div>
<script>
<?php echo 'do something here'; ?>
</script>
</div>
<?php } ?>
Using the above example can provide some unique results. Just remember that anything you do with php you can just echo out the result and slot it into the middle of your javascript.

Pass php variable via js/jquery redirect url function

In my php i'd like to redirect via javascript/jquery a url with a php variable via js function.
My js function
function Redirect(url){
document.location.href=url;
}
In my php page i try in this way but I fear there is a problem with the syntax in the $url.
if ($opz = 1){
$url = "index.php?opz=OK#PG2&id=" . $_GET['id'];
echo "<script>";
echo "$(function(){ Redirect($url); });";
echo "</script>";
}
If I try to redirect in this way everything works perfectly (no Redirect function).
echo "<script>
document.location.href='index.php?opz=OK#PG2&id=$_GET[id]'
</script>";
Can anyone suggest me what is the correct syntax to pass my php variable via the js Redirect function? Thanks.
Just change echo "$(function(){ Redirect($url); });"; to
echo "$(function(){ Redirect('$url'); });";
Notice the quotes. the url is to be passed to the Redirect function as a string. So enclose it in single quotes. like Redirect('$url');
your problem is simple:
echo "$(function(){ Redirect($url); });";
should be replaced with
echo "$(function(){ Redirect('$url'); });";
Why you are trying to redirect your webpage using javascript.
You can do it with PHP also. Use PHP header() function to redirect your page.
if ($opz = 1){
$url = "index.php?opz=OK#PG2&id=" . $_GET['id'];
header("Location:".$url);
}
Assuming the Javascript code being generated is OK try window.location
try like below
if ($opz = 1){
$param = 'opz='.urlencode("OK#PG2").'&id='.$_GET['id'];
$url = "index.php?".$param;
echo "<script>";
echo "$(function(){ Redirect($url); });";
echo "</script>";
}
and pick up opz using urldecode();
The problem is caused by the fact that your generated HTML looks like this:
Redirect(index.php?opz=.....);
As you can see, you're missing quotes.
To put a variable from PHP into JavaScript, I always use json_encode. This ensures that, no matter what I pass it, JavaScript will see the same thing. It takes care of quoting, escaping, even iterating over arrays and objects.

Echo a php output within a Javascript code

I couldn't get the code below to display the success word, any idea what's the problem with the code below?
Thanks in advance.
<script type="text/javascript">
function verification(){
var s = document.test_form.textfield.value;
if (s == "") {
alert("Please enter a value");
return false;
} else {
<?php echo "sucess"; ?>
}
}
</script>
You need to wrap your echo in an alert
alert("<?php echo 'sucess'; ?>")
Your output in javascript is:
else {
sucess
}
What this mean? Try something like this if you want to force output by PHP:
else {
<?php echo "alert('success');"; ?>
}
Or just return true to confirm submitting the form:
else {
return true;
}
You can do 2 things:
console.log("<?php echo 'success'; ?>"); // Will display a message into JS console
or:
alert("<?php echo 'success'; ?>"); // Will display a message into JS alert box
In your code, you only writing 'success' inside the javascript code, and when the browser will try to execute this JS code, it will not understand 'success'and it will throw an error.
If you want to display the text on your page, you can use inside a document.write:
document.write("<?php echo "success"; ?>");
Otherwise, you can use an alert() or console.log()
document.getElementById('body').innerHTML('<?php echo 'sucess'; ?>');
assuming that your body tag has the id body(<body id="body">)
EDIT. of course you can do that with every tag that has an id.
If you are getting PHP to write Javascript you might want to think about using a templating engine like Smarty or Twig.
For the case the file is a Javascript
If the original file is an external .js (not a .php) and is being read on the client side (browser) then it simply does not know how to parse PHP.
Therefore when the browser gets to:
} else {
<?php echo "sucess"; ?>
}
It simply does not recognize the <?php and thus is throwing an error.
Replace the PHP string by alert("success") or, if you do want to query the server and have the server output something take a look into Ajax.
For the case the file is a PHP and the Javascript code is embedded in the html
Replace the code by
} else {
<?php echo 'alert("sucess";)' ?>
}

Categories