getphphost

Add to favourites script with jquery and ajax

Posted by

 
Add to favourites
 
Scripting

Sun, Mar 19th, 2017 @ 7:04:16 PM - 

When listing many items on a site one can add a page with favourites per user. The user, when logged in, clicks on a button mostly in the shape of a heart after wich the item is added to the favourites page. It is the same principle as a wishlist. Clicking a second time on the heart or button removes the item from the wishlist or favourites.

The button in the shape of a heart

The button contains an id that is unique and gives a unique value of the item. For the heart, we have chosen the heart shaped glyph icon delivered by Bootstrap. The button is made invisible through css.


<button id="<?php echo get_the_ID();?>" class="addto" name="<?php echo get_the_ID();?>"><span id="hrt<?php echo get_the_ID();?>" class="glyphicon glyphicon-heart fav"></span></button>

Sending the value for id with jquery

In the footer, we put a javascript that is an alternative for a click function within the button code:

onclick="function();"

Here we go:


<script>
$(document).ready(function(){    
    $(".addto").click(function(){
        var getthevalue = $(this).attr("id");
        var spanid = "hrt" + getthevalue;
        var user = ;
        $.post("[MYDOMAIN]/wp-content/themes/[MYTHEME]/includes/addfav.php",
        {
          id: getthevalue,
          user_id: user
        },
        function(data,status){
            alert("Data: " + data + "\nStatus: " + status + "\nspanid: " + spanid);
        });
        document.getElementById(spanid).style.color = "red";        
        //$("$spanid").css("color", "red");
    });
});
</script>
$(".addto").click(function(){

In the second line of the script, we find ‘$(“.addto”)’ and then ‘click(function(){‘ the equivalent for
‘onclick=”function()’ in an element with assigned class “addto”.

This was the function to add a favourite to a database, but there is also a script to remove it from the database. The latter doesn’t operate from the common pages of the website but from a favourites’ page different for every user that can be mad visual per user when he is logged in.

The remove function starts from a ‘remove’ button on the user’s page:


<button id="" class="remove" name="">   
   <span class="glyphicon glyphicon-remove remfav"></span>
</button>

<script>
$(document).ready(function(){    
    $(".remove").click(function(){
        var getthevalue = $(this).attr("id");
        var user = ;
        $.post("[MYDOMAIN]/wp-content/themes/[MYTHEME]/includes/removefav.php",
        {
        id: getthevalue,
        user_id: user
        },
        function(data,status){
            alert("Data: " + data + "\nStatus: " + status);
         //alert(getthevalue + ", " + user);
        });         
    });
});
</script>

In both functions, the third and fourth line gives the gathered information for the userID and postID (here: propertyID, post of taxonomy type ‘property’)

The values for userID and postID are both sent to both .php files removefav.php and addfav.php with the method “post”. This .php file starting from within the javascript is what makes up the ajax.

In addfav.php and removefav.php we write the queries:

1. to add a favourite to a new database outside WordPress.
2. in the same .php file we indicate per post if he is favourite of a certain user
3. In a second .php file we delete favourites from the new database outside WordPress.
4. Again in this second .php file we also the postmeta if a favourite is removed.


<?php
$prop_id = $_POST['id'];
$user_id = $_POST['user_id'];

require_once('config.php');

// Create connection
$conn = mysqli_connect($mysqli_hostname, $mysqli_user, $mysqli_password, $mysqli_database);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO `glob_favorites`(`id`, `user_id`, `prop_id`, `love`) VALUES ('', '".$user_id."', '".$prop_id."', '')";

$sql2 = "INSERT INTO `wp_postmeta` (`meta_id`,`post_id`,`meta_key`,`meta_value`) values ('', $prop_id, 'favorite_of_', $user_id)";

if (mysqli_query($conn, $sql)) {
    echo "Added property number ".$prop_id." to user ".$user_id."!\n";
} else {
    echo "Error: " . $sql . "
" . mysqli_error($conn); } if (mysqli_query($conn, $sql2)) { echo "Added 'favourite of ".$user_id."' to property ".$prop_id."!"; } else { echo "Error: " . $sql2 . "
" . mysqli_error($conn); } mysqli_close($conn); ?>

And:


<?php
$prop_id = $_POST['id'];
$user_id = $_POST['user_id'];

require_once('config.php');

// Create connection
$conn = mysqli_connect($mysqli_hostname, $mysqli_user, $mysqli_password, $mysqli_database);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// sql to delete a record
$sql = "DELETE * FROM glob_favorites WHERE user_ID=".$user_id." AND prop_id= ".$prop_id;

$sql2 = "DELETE * FROM wp_postmeta WHERE post_id = ".$prop_id." AND favorite_of_ = ".$user_id";

if ($conn->query($sql) === TRUE) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}

if ($conn->query($sql2) === TRUE) {
    echo "Favorite deleted successfully";
} else {
    echo "Error deleting favorite: " . $conn->error;
}

$conn->close();
?>

When someone clicks on a grey coloured heart it means that he wants to add it to his favourites. The heart must be coloured pink while the post where it stands for is added to his favourites database. When the inverse happens, the heart should colour grey and the favourite should be taken out the database as well, just as we can on the favourites’ page but then with a red cross.

 
 

Related Posts

Posted in scripting,promotions

GETPHPHOST Easter promo
 

Leave a Reply

Your email address will not be published. Required fields are marked *

Login

Have an account?

Log in or sign up! It’s fast & free!

Register for this site!

Sign up now for the good stuff.

Lose something?

Enter your username or email to reset your password.

getphphost

Tech Magazine is Stephen Fry proof thanks to caching by WP Super Cache