Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mutaz's avatar
Level 7

Like button using Axios and Laravel

Hello everyone! I have created my first like button and instead of refresh page when user like the post , i have used axios it has success responce but the button style dosn't change , how can i change it..??

<script>
    document.getElementById('submit-button').addEventListener("click", function(event){
    event.preventDefault()
        const url = '/libraries/{{$library->id}}/like';
        axios.post(url).then(function() {
            var el = document.getElementsByClassName('submit-button');
// change the color style of button every time user click on it..
          console.log('test')
      })
  });
</script>
0 likes
10 replies
lbecket's avatar

@mutaz it means that

var el = document.getElementsByClassName('submit-button');

Doesn't do anything beyond just assigning an element reference to your variable. As @oussamamater indicated, you have to apply some action, whether it be the assignment of a class, the changing of a data property, etc.

2 likes
OussamaMater's avatar
var el = document.getElementsByClassName('submit-button');
el.classList.add("mystyle");

Change mystyle with the class you want to apply.

You can remove a class as well, if this is needed for your css to work

var el = document.getElementsByClassName('submit-button');
el.classList.remove("mystyle");

Edit: I assumed you are using blade with some vanilla Javascript, that will do the trick.

3 likes
mutaz's avatar
Level 7

@OussamaMater thanks but, how remove the class if user have cliked the button and class added on it ?

OussamaMater's avatar

@mutaz when a user clicks the like button you want to change the style from the current one to a new one.

So I assume you have a default css class let's call it default and a liked css class for when the library is liked.

So you want to add the css class to display the changes, and that's exactly what I have done.

1 like
mutaz's avatar
Level 7

@OussamaMater i understand you ,, but the idea when user click button it well change style but if the user clikc the button again how to check that..

OussamaMater's avatar
Level 37

@mutaz well that's your controller responsibility, make some checks, if it's already liked, return a 409 status which indicates that this like already exists, so you can do something like this

axios.post(url).then(function(response) {
   // this mean the library is not liked yet
    if (response.status != 409) {
        var el = document.getElementsByClassName('submit-button');
        el.classList.add("mystyle");
    }
})
2 likes

Please or to participate in this conversation.