PHP active write to DIV with arrays - javascript

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

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

Passing a PHP variable into a Javascript funtion

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>

Concatenate php variables and symbol to javascript function in php echo

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'].

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

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