简体   繁体   中英

How can I prevent an onclick JavaScript from running on page load?

I'm trying to attach a PHP script to a button so when someone clicks on it, I'm sent what page they're on. I have the PHP script written and I'm trying to attach it to a JavaScript onclick call. Here's what I have so far:

<button id="location">Click to reveal the page you're on</button>

<script>
    function send_sms() {
        var result  = '<?php locate_me(); ?>';
        console.log('send_sms');
    }
    document.getElementById('location').addEventListener('click', send_sms, false);
</script>

However, the JavaScript gets called when the page loads - not when the button is clicked - or maybe it's just the PHP that gets run. The console.log command does not get written on page load, but the PHP script is run. Very strange - at least to me.

I'm not proficient with JavaScript, but I thought the addEventListener() would prevent that from happening. What am I doing wrong?

Thanks, Frank

I'm not sure about what you mean by "revealing what page the user is on", but I'm thinking that's not relevant to the question, you're asking. I'm not too kean on running php scripts on the same file, I'm running my js on. As nice_dev suggested, I would make an ajax call to a seperate php file, in order to get live updates and not having your php variables pre-loaded.

So I would write my code like this: Your main file:

<?php // Result from your second php file ?>

 <script> // Ajax call $(document).ready(function(){ $("#location").click(function(){ var result = '<?php echo $variable; ?>'; $.ajax({ url: "somepage.php", type: "POST", data: {result:result}, success: function(result){alert(result }}); }); }); </script>
 <html> <body> <button id="location">Click to reveal the page you're on</button> </body> </html>

Your second file, which will handle your ajax request:

<?php 
$yourvariable = $POST['result'];

if isset($yourvariable){
// The php code you want to execute
}
?>

I hope this makes sense. Otherwise, I would be happy to elaborate. In summary, I would try to run your code on 2 files in a circular process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM