Passing a PHP variable into a Javascript funtion - javascript

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>

Related

Copy php variable to a JavaScript variable cause Design issue

**This is my code **
I am sending copying data from a php variable to a JavaScript variable here
<?php
include('includes/config.php');
include('includes/classes/Artist.php');
include('includes/classes/Album.php');
include('includes/classes/Song.php');
if(isset($_SESSION['userLoggedIn'])){
$userLoggedIn = $_SESSION['userLoggedIn'];
echo "<script>userLoggedIn = '$userLoggedIn';</script>";
// echo "<script>console.log('$userLoggedIn')</script>";
}else{
header('location:register.php');
And if i use the echo statement in the if statement here
it cause this. see the left side navigation bar;
Error image
And if i don;t use the echo statement the page is fine looks like this
Without error
I can't access the picture you uploaded right now, but I saw an error
echo "<script> var userLoggedIn = '" . $userLoggedIn . "'; alert(userLoggedIn); </script>";
Change the part we print on the screen in this way, data will be displayed on the screen.
I used this code inside the body of the html part and it works fine
<?php
if($userLoggedIn){
echo "<script>userLoggedIn = '$userLoggedIn';</script>";
}
?>

Writing php in Jquery Json object

I have a statement within my php-json-jquery object code that looks like so:
echo "{'year':'".$tree."'}";
i want to make the $tree variable a link so that a user can be able to click on it!
I have tried giving the variable an anchor [<a href></a>] tag but it hasnt worked.
As you want to echo json then you must do it with json_encode method available in php:
<?php
$anchor = "<a href='#'>".$tree."</a>";
$arr = array('year' => $anchor);
echo json_encode($arr); // prints {"year":"<a href='#'>date</a>"}
?>

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 active write to DIV with arrays

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>";

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.

Categories