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
<a id="apply" href="?id='.$id . '" class="btn btn-default" >Apply For Job</a>
here is function
<script type="text/javascript"> document.getElementById('apply').onclick = function() { <?php echo $uid=$_SESSION["id"]; $sql=mysqli_query($con,"select * from registration where usr_id='$uid'"); $row=mysqli_fetch_array($sql); $user_id=$row['usr_id']; echo $user_id; echo $post=$_GET['id']; $sql_post_query=mysqli_query($con,"select * from posts where post_id='$post'"); $row_post_query=mysqli_fetch_array($sql_post_query); $pos_title=$row['status_title']; $sql1=mysqli_query($con,"select * from job_applications where post_id='$post' && user_id='$uid'"); $row1=mysqli_fetch_array($sql1); if($row1) { //do nothing } else { $sql_query=mysqli_query($con,"insert into job_applications(post_id,user_id,post_title,date) values('$post','$user_id','$pos_title',NOW())"); if($sql_query) { echo "<script>alert('You have successfully applied for this job')</script>"; phpAlert( "You have successfully applied for this job" ); } }?> };
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