I am trying to call a javaScript function on click tag. But the function is getting executed automatically when I didn’t click on the link and I have also applied the onClick event listener for the function call but still, it is getting executed
here is the tag
JavaScript
x
1
1
<a id="apply" href="?id='.$id . '" class="btn btn-default" >Apply For Job</a>
here is function
JavaScript
1
32
32
1
<script type="text/javascript">
2
3
document.getElementById('apply').onclick = function() {
4
<?php
5
echo $uid=$_SESSION["id"];
6
$sql=mysqli_query($con,"select * from registration where usr_id='$uid'");
7
$row=mysqli_fetch_array($sql);
8
9
$user_id=$row['usr_id'];
10
echo $user_id;
11
echo $post=$_GET['id'];
12
13
$sql_post_query=mysqli_query($con,"select * from posts where post_id='$post'");
14
$row_post_query=mysqli_fetch_array($sql_post_query);
15
$pos_title=$row['status_title'];
16
$sql1=mysqli_query($con,"select * from job_applications where post_id='$post' && user_id='$uid'");
17
$row1=mysqli_fetch_array($sql1);
18
if($row1)
19
{
20
//do nothing
21
}
22
else
23
{
24
$sql_query=mysqli_query($con,"insert into job_applications(post_id,user_id,post_title,date) values('$post','$user_id','$pos_title',NOW())");
25
if($sql_query)
26
{
27
echo "<script>alert('You have successfully applied for this job')</script>";
28
phpAlert( "You have successfully applied for this job" );
29
}
30
31
}?>
32
}•;•
Advertisement
Answer
The reason why it runs without you executing or clicking it is because it is a php code. The php code is ran when the page is first loaded and the ‘onclick’ doesnt stop it. Javascript’s onclick event handles client side events, while PHP is server-sided.
In order to only run the php code when the link is clicked, you need to look into ajax calls or html forms, basically a way to communicate with your server