filemonczyk filemonczyk - 4 months ago 21
PHP Question

Adding like to item without rendering a new page in php

I'm trying to add like option to the item displayed on page.

So the work flow is as follows:

  1. User input data into form at url

  2. Search results pop up

  3. Like it or not

I did the following option:

<a href="like.php?type=gifLike&id=<?php echo $item->getId();?>">like</a>

and in like.php


but then after klicking on like, due to this action the previous search results are gone missing, so I'm getting blank page/notice errors because my previous input data from users is gone.

Is there any option to add this like and kind of stay on the same page?

ok I just realised that the search results are generated kind of 'randomly' base of given input so it looks like I have to use javascript here.


If you want to make request to server but keep user at the same page you should use JavaScript to make POST requests.

If you use jQuery then it's something like this:

     <!-- add jQuery -->
     <script src=""></script>

 <!-- ... -->

 <!-- adding class "like" so we can easily find all elements -->
 <a href="like.php?type=gifLike&id=<?php echo $item->getId();?>" class="like">like</a>
 <!-- repeat more a href... -->

    // $(function(){... executes after document load (DOM is ready)
        // add "onclick" event listener to all "a" with class "like"
        $('').on('click', function() {
            // $(this) - the element which was clicked
            // take its attribute "href"
            var url = $(this).attr('href');

            // use POST, not GET so browser and proxies will not cache it
            $.post(url, {}, function(result) {
                alert('You have liked it!');
                console.log(result); // you can get response from server

            // stop going to link URL in browser
            return false;