Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass PHP GET URL variables to open a window with Javascript?

I'd like to pass a PHP get variable from a link to Javascript so I can open a new smaller window with the appropriate content from the value passed to the URL .. I tried to do that below and I couldn't ... I'd really appreciate your assistance. The code below generates image hyperlinks that each have their ids from the database, so when the image is clicked on, a new window should be open but the ID should be passed to the javascript window.open method ... I tried to do that with AJAX to load the content according to the get variable but I couldn't do it!

<?php
require('../database/connect.php');
database_connect();
$query = "select * from Entertainers";
$result = $connection->query($query);
$row_count =$result->num_rows;

for($i = 1; $i <= $row_count; $i++)
  {
   $row = $result->fetch_assoc();


?>
<?php  echo "<a href='' onclick='window.open(profile.php?id=".$row['ID'].")'><img src ='../".$row['Picture']."' width='100' height='100' /> </a>"; } ?>
like image 353
Guy Rwayitare Avatar asked Dec 22 '12 04:12

Guy Rwayitare


1 Answers

Don't forget to quote the url in the Javascript open function. Also, did you consider using printf() for outputting?

$link =
'<a href="" onclick="window.open(\'profile.php?id=%d\')">'
. '<img src="../%s" width="100" height="100" /></a>' . PHP_EOL;

for($i = 1; $i <= $row_count; $i++) {
    $row = $result->fetch_assoc();
    printf($link,$row['ID'],$row['Picture']);
}

%d represents a decimal and %s represents a string in the above string (hence the $link). Another tip: if you have no particular reason to use the for loop, using a while loop instead will make your code cleaner and shorter.

while ($row = $result->fetch_assoc()) {
    printf($link,$row['ID'],$row['Picture']);
}
like image 106
inhan Avatar answered Sep 18 '22 17:09

inhan