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>";
.......
......
....
Related
I have a variable named $path. I want to pass this variable from PHP to a javascript function.
<button onclick='myFunctionContact(\"" . $row1['id'] . "\")'>
<img border='0' alt='Contacts' src='".$imgpth."peoplesmall.png'>
</button>
<script>
function myFunctionContact(id) {
window.open('!!!$path should go here!!!'+id, '', 'toolbar=no,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=400');
}
</script>
How do I get the URL in path to display inside of the function, in the desired place?
I tried printing the variable into a javascript variable and then placing that variable into the function, but the popup window no longer works when I do that.
function myFunctionContact(id) {
var test1 = <?php echo $path; ?>;
window.open(test1 +id, '', 'toolbar=no,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=400');
}
I Know I am doing it wrong, but I have no idea how. Any advice would be greatly appreciated.
I think the problem is how you are echo the path:
Instead of:
var test1 = <?php echo $path; ?>
i think it should be
var test1 = <?php echo '"'.$path.'";'; ?>
You can always use a hidden input field, and set it's value to whatever you need to be used in your JS code, then grab that value of in your JS, or maybe try an ajax call to get the value you need.
json_encode() fixed the problem.
var myValue = <?php echo json_encode($path); ?>;
The path needs to be a quoted string. The end result of your echoed string has to, itself, contain quotes.
Assuming $path is a string, window.open is expecting a quoted string as the parameter.
function myFunctionContact(id) {
window.open(' . $path . ' + id, '', 'toolbar=no,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=400');
}
</script>
I finally got the php variables to pass to the javascript function but they are passing as multiple and getting a warning.
Use of undefined constant app_name - assumed 'app_name'
How can i define the variables?
echo('<li> <a href="#" onClick="runthis(\''.str_replace("'", "\\'", $row[activity]).'\',\''.str_replace("'", "\\'", $row[app_name]).'\');">');
Javascript
function runthis(activity) {
alert(activity);
//$('#live-area').load('../assets/php/multibox.php?id=' + activity);
}
I am trying to concat $row[activity] and $row[app_name] with /
my php explodes on / and breaks into variables
UPDATE
Here is what im doing with the data.
if (isset($_GET['id'])) {
$app = $_GET['id'];
$array2 = explode('/', $app);
$activity = $array2[0];
$app_name = $array2[1];
$SQL1 .= "WHERE activity = '$activity' ";
}
I don't think im handling the string properly.
What should this look like?
I updated the echo onClick to this
echo ('<li> <a href="#" onClick="runthis(\'' . $row['activity'] . '/' . $row['app_name'] . '\')">');
It passes correctly to javascript but when $_GET loads it i get no results
You're dumping PHP output into Javascript context. Use json_encode() to do this properly:
echo '<li>..... ', json_encode($row['activity']), '</li>';
As it stands right now, your array keys aren't quoted, which'll probably cause PHP to issue various warnings, and those warnings will get output in your JS code, causing syntax errors.
json_encode() will take care of ALL the necessary quoting/escaping for you. It'll also be far more readable/maintainable than the abomination you've come up with.
comment followup, split onto 3 lines for a bit more legibility:
echo '<li> <a href="#" onClick="runthis(';
echo json_encode("{$row['activity']}/{$row['app_name']}");
echo ')">';
You're getting Use of undefined constant app_name - assumed 'app_name' because you're saying $row[app_name] instead of $row['app_name'].
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
Once again I'm posting for something that I've never dealt with or have not found the answers with my google searches.
I have a web app, that I want to turn on a "logging" section.
I want an empty DIV to have data written to it (they're array CURL requests and json responses).
I have found how to Jquery write to a div, but this doesn't work with arrays. Does anyone have a better suggestion for me?
Code:
<script>
function updateProgress(progress){
$("#progress").append("<div class='progress'>" + progress + "</div>");
}
</script>
<div id='progress'></div>
in PHP:
echo "<script language='javascript'>parent.updateProgress('$response');</script>";
Error: Array to string conversion
use .html() to write in to div
<script>
function updateProgress(progress) {
$("#progress").html("<div class='progress'>" + progress + "</div>");
}
</script>
PHP:
echo "<script>";
echo "$(document).ready(function() {";
echo "updateProgress(" . $response. ");";
echo "});";
echo "</script>";
The problem is inside your PHP code. The variable $response is an array and you're attempting to convert it to (cast it as) a string, hence the error, "Array to string conversion".
Basically, you're doing this:
echo (string)array('value1', 'value2'); // Notice: Array to string conversion
If this is just a basic array (as the above example is), you can easily fix this by using implode. For example:
echo "<script language='javascript'>parent.updateProgress('" . str_replace("'", ''', implode(', ', $response)) . "');</script>";
If it's more complex (multi-dimensional array), you'll need to do some further processing to get only the values you want to show on the page.
The way you call this function parent.updateProgress('$response'); is wrong, you need not remove parent from invoking statement something like this.
echo "<script language='javascript'>updateProgress('".$response."');</script>";
//-----------remove parent from here^
Now this function updateProgress will be invoked successfully.
If $response is an array, and you want to display this as string then you can use it.
$response = implode(", ", $response);
echo "<script language='javascript'>updateProgress('".$response."');</script>";
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.