Reputation: 35
I want to write Jquery code inside PHP
tag. I wanted to do this so that I can perform AJAX
after that.
I have tried to echo it, but it doesn't work.
<?php
require("conn.php");
$rs = mysql_query("select * from food order by LENGTH(price), price");
if($rs!=false && mysql_num_rows($rs)>0){
$counter ++;
while($row = mysql_fetch_array($rs)){
echo '
<script src="jquery.js">
<script>
$(document).ready(function(){
$("#'.$row["code"].'").click(function(){
echo "clicked";
});
});
</script>
';
}
mysql_free_result($rs);
}else{
echo mysql_error();
}
mysql_close();
?>
Upvotes: 0
Views: 880
Reputation: 6608
Here's a small rearrangement of your code.
<?php
require("conn.php");
$rs = mysql_query("select * from food order by LENGTH(price), price");
if($rs!=false && mysql_num_rows($rs)>0){
$counter ++;
while($row = mysql_fetch_array($rs)){
echo '<a class="row_food">'. $row["code"] .'</a>';
}
mysql_free_result($rs);
}else{
echo mysql_error();
}
mysql_close();
?>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$('.row_food').click(function(){
alert("clicked");
return false;
});
});
</script>
You don't have to echo the javascript code every time in the loop! You only need to echo the content from your db inside the loop.
In the javascript/jquery, you could bind the click event to the element and do whatever you needed.
Hope it helps.
Upvotes: 2