0

I have a like button. The php behind it works as it should. But it refreshes the page. Is it possible to write a javascript between the HTML and the PHP? For example: HTML:

<input type="button" id="like_button"><img src="images/like.png"><?php echo $getVideo["likes"];?></button>

And when clicking on that button, the javascript triggers the file like_button.php, which looks like this:

<?php 
require_once "data_inc/database.php";

   $like = new videos();
   $like->likeButton($_GET["id"]);

No link out there shows how it would look like, while having OOP php. If someone could provide a javascript, it would help everyone who are currently facing this. How would the javascript look like? Thanks.

1

1 Answer 1

0

You should make AJAX call. for example:

<input type="button" onclick="get_like()" id="like_button"><img src="images/like.png"><?php echo $getVideo["likes"];?></button>

<script>
    function get_like() {
        fetch('http(s)://<server>/like_button.php', {'method': 'get'})
            .then(data=> {})
            .catch(error => console.log(error));
        
    }
</script>

You can read more on fetch https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Otherwise you can use any ajax call, for example from jQuery if you like.

For this purpose I would also consider using <button> instead of <input>

Sign up to request clarification or add additional context in comments.

3 Comments

The code didn't work. I tried this $( "#like_form" ).on( "click", function(data) { console.log('Form triggered'); fetch('like_button.php', {'method': 'get'}) .then(data=> {}) .catch(error => console.log(error)); }) which outputs "Form Triggerd", but doesn't trigger the php file..
don't you have a <form> somewhere ? did you change <input> to <button> to avoid triggering sending form ?
With this code only in <body> tag and with filled in address it works fine. If you have other code you should post it or modify the answer to suit your needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.