I want to call a JavaScript function inside PHP code,This function return a number, the Result for example is : http://localhost/1.php?id=fn(3)
as you see this function cannot be interpreted by the browser I already tried ' ' or " " But I get the same problem, normally I must receive for example http://localhost/1.php?id=3
Any help on this problem would be greatly appreciated! Thank you in advance!
<body>
<script type="text/javascript">
function fn(a)
{
var table = document.getElementsByTagName("table")[0];
var res=table.rows[a].cells[0].innerHTML;
return res;
}
</script>
<table class="table " id="tableId">
<?php
$bdd = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '');
$reponse = $bdd->query('SELECT * from jeux_video');
while ($donnees = $reponse->fetch()){
echo "
<tr onclick=\"location.href='1.php?id=fn($donnees[ID])'\">
";
?>
<td id="td1"><?php echo $donnees['ID']?></td>
<td><?php echo $donnees['nom']?></td>
<td><?php echo $donnees['possesseur']?></td>
<td><?php echo $donnees['prix']?></td>
</tr>
<?php } $reponse ->closeCursor(); ?>
</table>
</body>
The string you're putting on the href won't be parsed as a javascript expression, but just as a string.
You need to output a valid javascript statement for the fn call to execute:
echo "<tr onclick=\"location.href='1.php?id=' + fn(".$donnees[ID].")\">";
This will output:
<tr onclick="location.href='1.php?id=' + fn(3)">
PHP runs on the server, and Javascript on the client. That's the rule. If you want PHP to output a value anywhere in your document, you need to do it with PHP:
echo "<tr onclick=\"location.href='1.php?id=' + fn(" . $donnees[ID] . ")'\">"; // ...
As it is, this is likely the exact markup that is being output:
<tr onclick=\"location.href='1.php?id=fn($donnees[ID])'\">
Which, to Javascript, makes no sense.
This doesn't do what you think it does:
location.href = '1.php?id=fn(3)'
JavaScript isn't going to automatically evaluate code inside of a string. You have to execute the code itself and concatenate its result to the string. Something like this:
location.href = '1.php?id=' + fn(3)
Related
I have
function delImage(posteId,imagebinId) {
$.get("<?php echo base_url('/Home/deletePostimage/') ?>");
return false;
}
i want to be like /Home/deletePostimage/posteId/imagebinId
i tried
$.get("<?php echo base_url('/Home/deletePostimage/')+posteId+"/"+imagebinId ?>");
but it divide the two numbers
like posteId=5 imagebinId =2
the results will be
/Home/deletePostimage/2,5
the params from
<a class="postimgsd" onClick="if(confirm('Are you sure you want to delete this image ?')){delImage(<?php echo $value['id'],$get_images[0]['binId']; ?>); rmItem(<?php echo $i; ?>);}else{} ; " >
With ES6, you can do this with string interpolation:
$.get(`<?php echo base_url('/Home/deletePostimage/${postId}/${imagebinId}') ?>`);
Without ES6, there is another answer that answers it, or use this:
var url = '/Home/deletePostimage/' + postId + '/' + imagebinId;
$.get("<?php echo base_url('" + url + "') ?>");
Furthermore, the code that calls this function should actually be:
<a class="postimgsd" onClick="checkDeletion()" />
<script type='text/javascript'>
function checkDeletion() {
if(confirm('Are you sure you want to delete this image ?')) {
var postId = <?php echo $value['id']; ?>;
var imagebinId = <?php echo $get_images[0]['binId']; ?>;
delImage(postId, imagebinId);
rmItem(<?php echo $i; ?>);
}
}
</script>
You need to keep in mind that PHP is processed on back-end before send the html to your user browser. That said, everything between php tags (<?php ... ?>) is rendered/processed before javascript even exists.
So if you put any JavaScript code inside your PHP code it won't work.
To make it work and be clean, do something like this:
function delImage(posteId,imagebinId) {
let url = "<?php echo base_url('/Home/deletePostimage/') ?>";
$.get(url + posteId + "," + imagebinId);
return false;
}
I want to passing variable from php to Javascript. But it can only passing integer type. When I pass value that is not integer, the variable value is undefined.
<?php
$sqlCall="SELECT * FROM table";
$resCall=mysqli_query($con, $sqlCall);
while($row=mysqli_fetch_array($resCall)){
echo "<tr>";
echo "<td>".$row[id]."</td>";
echo "<td>".$row[name]."</td>";
echo "<a onclick='edit(".$row['id'].",'".$row['name']."')'>Edit</a>"
?>
and here is my JavaScript:
<script>
function edit(id, name){
document.getElementById('edit_id').value = id;
document.getElementById('edit_name').value = name;
}
</script>
The problem comes from the single quotes ' use " instead like :
"<a onclick='edit(".$row['id'].","".$row['name']."")'>Edit</a>"
My code :
<?php echo ' <script>var p=0;for(var i=0;i<=5;i++){p++;}alert("ques".p);? >
The value of p is displayed as 0.
You need to close your php tag properly as well as the <script> tag like so:
<?php echo '<script>var p=0;for(var i=0;i<=5;i++){p++;}alert("ques" +p);</script>'; ?>
Also, change the . to a + as you are concatenating in javascript not PHP
The correct answer is:
<?php echo '<script>var p=0;for(var i=0;i<=5;i++){p++;}alert("ques" + p)'; ?>
Strings in single quotes will be escaped, use quotation marks instead.
<?php echo "<script>var p=0;for(var i=0;i<=5;i++){p++;}alert('ques' +p);</script>"; ?>
The mistakes in your code are,
Close your php tag properly - ?> instead of ? >
Close the script tag in the end - </script>
Close the single quote you started with echo
The correct code would be
<?php echo '<script>var p=0;for(var i=0;i<=5;i++){ p++; } alert("ques" + p); </script>'; ?>
I am trying to set some fields of a form with the values of an array.
I have an array like this:
Array
{
'elementID1' => Array
{
'id1' => 'some value',
'id2' => 'some value',
'id3' => 'some value',
...
}
'elementID2' => Array
{
'id1' => 'some value',
'id2' => 'some value',
'id3' => 'some value',
...
}
...
}
The array is filled with the response of a webservice to whom I sent some parameters with a form. Once I filled the array, I draw a table and iterate over the array.
<table width = "100%" border = "1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>View details</th>
</tr>
<?php
foreach($array as $id => $detail)
{
echo "<tr>";
echo "<td>";
if(array_key_exists('id1', $detail))
echo $detail['id1'];
echo "</td>";
echo "<td>";
if(array_key_exists('id2', $detail))
echo $detail['id2'];
echo "</td>";
echo "<td>";
if(array_key_exists('id3', $detail))
echo $detail['id3'];
echo "</td>";
echo "<td>";
echo "View more";
echo "</td>";
echo "</tr>";
}
?>
</table>
Now, here comes the problem, as you can see there is a fourth column called View details, this column is filled with a hyperlink that calls a javascript function with the elementID value of the specific row as parameter.
A little more below I have the script:
<script>
function equisYe(id)
{
var equis = "<?php echo $array['" + id + "']['IncidentID']; ?>";
alert(equis);
}
</script>
When I click on the hyperlink doen't happen anything, I think the problem has something to do with the special characters inside the quote punctuations. In my browser, when I inspect one of the hyperlinks, it shows the following message inside de scripts tags:
function equisYe(id)
{
var equis = "<br />
<b>Notice</b>: Undefined index: + id + in <b>
";
alert(equis);
}
That means, for some reason, the strings aren't concatenating, and if I delete a 'p' from php tag in the equis var like this:
var equis = "<?ph echo $array['" + id + "']['IncidentID']; ?>";
Then the alert shows this:
"<?ph echo $array['10']['IncidentID']; ?>"
So, it works when it doesn't have the php tags.
The other answer is correct, but not explaining it at all (or even politely). The PHP stuff runs before your Javascript stuff does. You'll never get this to work this way, unfortunately. If it was the other way around, it might work, but this isn't going to work the way you have it.
The only way to have something like this working is to have the ID value chosen in advance and have PHP set something in Javascript. Javascript can never set a PHP value simply by virtue of PHP being run prior to the page being served and Javascript being run after the page is served.
dude... javascript executes on client(browser) and php on server; you CANNOT do that
try to use <? ?> instead of <?php ?>
Everyone is correct in that you can't simply call PHP functions from Javascript without performing some kind of HTTP request.
Since you already have the "IncidentID" in php while you're generating the page, you can simply write it to the page.
instead of
echo "<td>";
echo "View more";
echo "</td>";
do
echo "<td>";
echo "View more";
echo "</td>";
You can use data attribute to pass the $id to js, always using the DOM.
Check this: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
Then use a click event in "view details" to get the data from element and trigger the function, this way you will be abble to work with it
I have this working script yet when I change it to retrieve(supposedly) the value inside $_SESSION["username"], it doesn't retrieve anything. The whole page is saved as .php as I am using some codes that uses PHP.
Code:
echo "<script type=text/javascript>";
echo "var hidden = false;";
echo "function actiondb1() {";
echo "if(!hidden) {";
echo "document.getElementById(\'clickdb1\').style.visibility = \'hidden\';";
echo "document.getElementById(\'db1\').style.visibility = \'visible\';";
echo "document.getElementById(\'db1\').disabled = false;";
echo "document.getElementById(\'db1\').value =".$_SESSION["username"];.";";
echo "}";
echo "}";
echo "</script>";
How can I make the script to properly retrieve the data inside $_SESSION["username"];?
Observe that, for instance, if the value of $_SESSION["username"] is John, your echo will be generating this result:
document.getElementById('db1').value = John;
But John is supposed to be a string and should be wrapped in quotation marks, otherwise JavaScript will understand it as a variable name (which value will be probably undefined).
As Havenard mentioned, this line is missing Javascript single quotes to properly denote a string variable:
echo "document.getElementById(\'db1\').value ='".$_SESSION["username"];."';";
However, you really shouldn't print JS out with PHP if you can help it. Though iatboy's answer answer won't ultimately fix your bug, it is a much cleaner way of doing things.
?>
<script type=text/javascript>;
var hidden = false;
function actiondb1() {
if(!hidden) {
document.getElementById('clickdb1').style.visibility = 'hidden';
document.getElementById('db1').style.visibility = 'visible';
document.getElementById('db1').disabled = false;
document.getElementById('db1').value ='<?php echo $_SESSION["username"];?>';
}
}
</script>;
<?php
Did you start session in this page?If you didn't,use the follow code to start session.
session_start();
Then change your code to
echo "<script type=text/javascript>";
echo "var hidden = false;\n";
echo "function actiondb1() {\n";
echo "alert('".$_SESSION['username']."')\n"; //test code
echo "if(!hidden) {\n";
echo "document.getElementById('clickdb1').style.visibility = 'hidden';\n";
echo "document.getElementById('db1').style.visibility = 'visible';\n";
echo "document.getElementById('db1').disabled = false;\n";
echo "document.getElementById('db1').value ='".$_SESSION["username"]."';\n";
echo "}\n";
echo "}\n";
echo "</script>";
it will be ok.