Jump to content

[SOLVED] use javascript in php in a link


tanveer

Recommended Posts

I am running a query based on a criteria for showing a list of all users and there I put a link as edit and now want to add a javascript which will give me a input box with choice of yes and cancel.

How to do that?

Below is a sample code:

 

while($row=mysql_fetch_row($result))
{ 
        echo "<tr>";
if( date($row[4]) == date('Y-m-d') ) 
{
  for ($i=1;$i<$num_fields;$i++)	 
    {
		echo '<td bgcolor="#87564d"><b>';  // to make bold the message
		echo $row[$i]; 
		echo '</b>';
    }

  	 echo "</td><td><a href=delete.php?id=" . $row[0] . " onclick=test()>Delete </a>";
   	 echo "</td><td><a href=edit_user.php?id=" . $row[0] . ">Edit</a>";  
 echo '</td></tr>';
    } // end if block

Link to comment
https://forums.phpfreaks.com/topic/38131-solved-use-javascript-in-php-in-a-link/
Share on other sites

that should work as long as you have a predefined javascript function called test() in your header somewhere.  Also, u need to change onclick=test() to onclick=\"test()\"

 

in other words, it needs to be enclosed in quotes.

 

in fact you need to enclose all of your anchor elements in quotes...

One more thing to ask. Now that its checking if user is pressing yes/no so now how to rediret them to the specified php page as currently it redirects to the php pages declared in hyperlink despite their input? Now how to make them work from javascript function test().

 

PHP code:

echo "</td><td><a href=delete.php?id=" . $row[0] . ">Delete </a>";
echo "</td><td><a href=edit_user.php?id=" . $row[0] . " onClick=test()>Edit</a>";  

 

JavaScript Code:

<script type="text/javascript">
<!--
function test(){
var answer = confirm("R U Sure you want to delete this record ?");
if (answer){
	alert("checking Yes")
	window.location = "edit_user.php?id=" . $row[0] . "";

}
else{
	alert("Clicked NO!") 

}
}
//-->
</script>

THis is working fine except its not passing the real value to edit_user.php page. its just passing the charater 't' instead of value though its printing the value right in alert statement.

 

<script type="text/javascript">
<!--
function test(t){
var answer = confirm("R U Sure you want to delete this record ?");
if (answer){
alert("Value="+t)   // its printing correct value here
   	window.location = "http://localhost/project/edit_user.php?id=t";  // just passing as 't' not the value

}
else{
	alert("else block")

}
}
//-->
</script>

 

php code:

echo "</td><td><a href=delete.php?id=" . $row[0] . ">Delete </a>";
echo "</td><td><a href='#' onClick=test(" . $row[0] . " ) >Edit</a>";  

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.