A little bit of everything…
RSS icon Home icon
  • AJAX add content to favourites script

    Posted on July 5th, 2009 Aleix 12 comments

    It has been a while since I last wrote a post but, as I said, I’d be back again! Not that I have much free time, but I’ll keep posting stuff whenever I’m inspired and have the time to do so :)

    Today’s post is a response to deepali’s comment here. There are lots of ways to achieve the result, and this is just my approach to the issue. The following script allows users to favourite/unfavourite posts, pictures, etc. with AJAX, PHP and MySQL, without reloading the whole page. A clear example of that is Youtube.com, where users can add videos to their favourites with just one mouse click and without reloading the whole content of the page.

    View a working demo of the script here (note: if it temporarily performs weirdly is because it uses a single user ID, therefore all the people who try the demo use the same session)


    Preliminary note

    First of all, this script is recommended for people who already have some knowledge of PHP (and possibly JavaScript too); otherwise it might be confusing. Secondly, you will need your site to work with PHP Sessions for the script to integrate to it (unless, of course, you change its code to work without sessions).

    Because of the extension of the code and also the number of files involved, I thought it would be more convenient to pack the script code into a ZIP file instead of dumping the whole of it here. So this post is just my comment to the code of the script, which you can download here:

    Download AJAX Favourites script [ZIP, 29 kb]

    (If you cannot open the ZIP file, I recommend you use PeaZip to do so (Freeware))

    Once you’ve downloaded it, you can upload it to your server and use it almost straight away. However, firstly you will have to spend a couple of minutes setting up a small MySQL table and configuring some variables. I strongly recommend you to read the following guide in order to get the script to work correctly.


    1. Setting up the MySQL table

    You should create a new MySQL table named ajaxfavourites and containing at least the 2 required columns, named user and favid (remember those names are case sensitive). The recommended data type is numeric.

    • user column will store the numeric ID of the user which favourited a content.
    • favid column will store the numeric ID of the favourited content.


    2. Configuring the script essentials

    Once you’ve uploaded the script to the server and set up the MySQL table, it’s time to change a few variables for the script to work well:

    1. In favscript/mysql.php, you need to configure the variables required for connecting to the MySQL database where the table you just created is located. You will need the database name, database host (on default: localhost), database administrator and password.
    2. In favscript/favouritescript.php, you need to make a very essential change. Read carefully below.

    At the very top of favscript/favouritescript.php, you will see there is a variable to be configured ($favid); it comes with a sample value (50) which you must change for the script to integrate in your site. I left the sample value because every website works in a different manner and it’s the work of each to configure it accordingly to his own project. What you need to do here is to add code for retrieving the variable from your site (in other words, you need to add code with which the site will tell the script WHAT is being favourited). For $favid you’ll need dynamic code for setting as value of the variable and ID or a string which identifies the favourited content in a unique way. A quick example of how could (depending on your site) it look like:

    $favid= $_GET['pageid'];
    

    Once you’ve configured this correctly, you can proceed with the following steps.

    In step 4 we will configure another essential setting.


    3. Overview of the script elements

    Let’s take a look on the function of each file which is included in the script. This is a quick description; in the next steps a more in-depth description of each is made:

    1. index.php is actually a sample page which contains the necessary code snippets you must include in your page for the script to work.
    2. favscript/addremove.php should not directly be accessed by the users. When they add or remove a favourite from the frontend, AJAX calls this PHP file to process the request. This file contains the PHP code to make the MySQL queries for adding or removing favourites from the database.
    3. favscript/ajax.js contains JavaScript code for making AJAX work, passing the requests to addremove.php, and favourite button toggle effect. Must be included in the frontend pages for the script to work.
    4. favscript/favouritescript.php identifies the user and content which is being favourited; it also checks – on page load – if an article is already favourite or not to display the page accordingly. Must be included in the frontend pages for the script to work.
    5. favscript/mysql.php contains the variables and code to connect to the MySQL database.
    6. favscript/styles.css contains a couple of sample styles which can be freely modified.

    And now, an in-depth explanation of how each part works.


    4. index.php

    First of all, you should configure the first part of the code for it to work with the session settings of your site. You will need to dynamically assign the current logged in session user id as value of $_SESSION['userid'].

    Check the source code of this file and you will notice there are several ‘blocks’. First there is the favourites script block, which includes parts of the script: optionally CSS, and required ajax.js and favouritescript.php. You don’t need the CSS if you decide not to use the favourites status bar. This bar is the second portion of code, and can be removed if you don’t want it to show. To do so, you need to remove this block of code and also remove some code from ajax.js. You may also style it in any way you want.

    The third block (random page content) has sample content and represents this is the code of your site.

    The fourth block (favourites button) allows the user to add or remove the content as favourite. It is based on a JavaScript clickable image button, but can be changed to text link by making some tweaks in the code of index.php and last lines of ajax.js.

    The image used for the button is a sample image, you may replace it with whatever other images you want, but make sure they’re named button0.jpg and button1.jpg respectively for ‘add as favourite’ or ‘remove’. They must be placed in the images folder.


    5. favscript/addremove.php

    It isn’t really necessary to comment the code of this file, as it is pretty self-explanatory and some brief comments are already made in the source code.

    Important security note! it would be possible to exploit the script through this file if a simple security measure was not applied!

    The problem was, that anyone knowing the URL to that file could access it directly from the browser and pass variables to it (as GET method is used to pass the variables).

    Example: anyone could arbitrarily add or delete favourite X from user Y, from the database by inputting the following URL:

    …favscript/addremove.php?user=Y&favid=X

    Therefore, to fix the problem the USER variable is not passed via GET but through SESSION variables. Any attempt to access the script without a valid user ID will abort the operation, and users who nevertheless do can only add or remove their own favourites. It is important, as previously pointed, that when you integrate the script in your site you integrate the sessions too! The script will assign as USER ID for each query the ID assigned to the user by the session variable.

    However the bug partially persists, as a user with a valid session can still arbitrarily change his own favourites by using this method, by inputting values to the FAVID variable in the url. To prevent SQL injection and make this bug less dangerous, mysql_real_escape_string() is used to escape those inputs. Any ideas for fixing that (allowing AJAX-only access) are welcome, but it will be difficult because AJAX is also client-side…


    6. favscript/ajax.js

    For a more detailed explanation of how it works, please refer to this other post of mine, as the script is based on it.

    The only difference is the last part of the code, which controls the favourites status bar behaviour and the button toggle. Be careful when modifying that code, as it can make the whole script no longer work.


    7. favscript/favouritescript.php

    The first part of the code of this file is already explained in Part 2 (Configuring the script essentials).

    The other function of this file is to find out, when content is loaded by the user, whether it is part of his favourites list or not. To do so, it queries the database and obtains the number of rows matching both $user (session user ID) and $favid. If it is not a favourite, then the number of returned rows should be 0 ($matches == ‘0′) whereas if the content has been favourited the number of returned rows should be 1. The result is passed to index.php as $matches; for displaying the page elements (e.g. favourite button and status bar) accordingly.


    8. Practical uses

    The greatest utility of this script lies in the MySQL table where records of favourites are added. You can easily code other simple scripts which retrieve the stored records for:

    1. Showing how many people have favourited a specific content,
    2. Showing what the favourites of a specific user are,
    3. Showing the number of favourites each user has,
    4. Send a notification of content changes to the users which have favourited the specific content,
    5. Etc.

    The only limit is the limit of imagination ;)


    9. Conclusion & disclaimer

    I think the explanation above should suffice, but as some might be confused, please ask any doubts by commenting this post and I’ll try to resolve them.

    About possible bugs and code optimisation: this script is experimental, even when it can be used in live sites. It might be possible to optimise some portions of the code, and it is possible that there are bugs, which I’d be thankful you report here so to correct them. Please report as well any errors you might find in this guide!

    If you use the script, my advice is that you get to understand how it works rather than just set it up and put to work something you ignore how it does what.

    The script is provided as-is and I assume no responsibility on its operativeness and eventual conflicts with your specific site.

    I hope it is useful!

     

    Related posts:


     

    12 responses to “AJAX add content to favourites script”

    1. Hello Aleix,

      Right now i am so overwhelmed because not only you have solved my problem but here you have mentioned my name also. :)

      Defiantly i have downloaded your script.And right now i am trying your code according to my requirement.

      I will get back to you as soon as possible.

      Once again thank a lot for your article. I am sure it will help number of people out there who are really looking for it.

      You rock man! :)

    2. Hello Deepali,

      Thanks for your encouraging comment! You’ll be one of the first trying this script, so if you have questions or would like to report errors or bugs, I’d be glad to help, just let me know.

      Greetings :)

    3. Hello Aleix,

      Your code is simply works for me. But where actually i want to impliment it, getting problem. though its not related to your code.but i can ask geuinous to help me right? :)

      so my problem is as follows.

      I have page games.php. using htaccess i have been using this url,

      sitename/games/gamesname

      Using gameid i can see different game pages. Now on this gamesname.php,i am trying to build up add favorite games option. using ajax i want to do that.

      Here on particularly on this page. where my site url is like this,

      sitename/games/gamesname

      with this path its showing me this error

      Quote:
      The page cannot be found

      The page you are looking for: /games/sliderman/addremovefav.php?t=1246876451&gameid=11240
      Can anyone tell me how can i work this out?

      addremove.php
      gamepage.php
      ajaxdev.js

      everything is in the same folder.When i add this

      var url = ‘../../addremovefav.php’;

      into my addfav.js, it showing me the following error

      The page cannot be found
      The page you are looking for: /addremovefav.php?t=1246876921&blogid=11240

      why this extra “/” is coming?

      I hope you ll understand what i am asking here. because its bit confusing for me as well.

      please help me.

      Thnaks in advance.

      If you don’t get time,then its fine. But your suggestion may help me too.:)

      But for the other pople who want to use this module want to tell you something that, this module works like charm!!!

      So,Go ahead with it. :)

      Regards!!!

    4. Hello again! Not sure how can this be fixed as I never use htaccess URLs. I’ll think about it and if I happen to have an idea I’ll let you know. In the meantime, give a try to using a full url when referencing the script location instead of a relative one (in other words and as an example, try http://www.xyz.ab/folder/file.php instead of ../file.php)

      Regards

    5. Hello Aleix,

      Thanks for your suggestion. I am working on it. But as far as your module is concern, its working!!

      Keep up doing good work!! :)

      I am waiting for your next article.

      Regard!!

    6. Hi deepali,

      Not sure if this addresses your htaccess issue, but thought perhaps it could be of your interest:

      http://stackoverflow.com/questions/521019/htaccess-redirect-to-script-in-subdirectory

    7. Hello Aleix, :)

      Sorry for the late reply. Thanks for the link. I think i should learn how build up htaccess, then only i would be able to find out what is problem and how can i get rid from it. right?

      Anyways thanks for your reply.

      Regard!!

    8. Hello Aleix,

      I hope you are finished with your exams by now. Because you have not updated any new article yet. people here are waiting for that. :)

      Could you please the check the following link,

      http://net.tutsplus.com/tutorials/javascript-ajax/create-a-twitter-like-load-more-widget/

      This is David Walsh’s article where he has shown how to give hover effect and show the read more link. I want something like this. On hover i want to show a delete (X) button so user can easily delete the record with AJAX.I tried using his code but it seems its not working for me.:( I am trying it.

      So, could you please suggeste me some link for this module?

      BTW, i have solved my htaccess issue.

      Your help ll be greatly appreciated as always!

      Regards!

    9. Hello Deepali,

      Apologies, I think I overlooked this comment of yours and hence there was no answer from me. I’ll take soon a look at that!

      See you around

      :)

    10. Hi again,

      I know it might sound redundant, but if you’re implementing his system for your close button, please check carefully that you meet the requirements specified in the linked tutorial for it to work (under section “Assumptions”; especially Mootools + More). As the script involves Mootools I can be of very few help here, because even though I’ve used them now and then, I’ve never really learned much about how they work.

      The code in this post can be helpful for performing the “delete” operation when the user clicks the X button, but for the cool sliding/fading effects which JavaScript allows you’ll have to write extra code or use JavaScript frameworks.

      Regards

    11. Hello Aliex,

      I am sorry i too overlooked your reply. i have solved my problem with the help of this link

      http://www.pmob.co.uk/temp/single-line-dropdown.htm

      Anyways thanks for your reply. :)

      P.S- I have keep on my eye on your latest work.
      Hope ll get new things to learn soon.

    12. Hello Aleix,

      I hope you are doing good. Just dropping in to say “hi!”.

      I was wondering that why don’t you have contact form here. I wanted to wish you on Christmas and New year.

      Anyways its never to late right?

      Wish you a very Happy New Year!!

    Leave a reply