Search code examples
jquerypostjquery-postjquery-click-event

jQuery - Add to Favourites


I have a loads of reports. Each report as it's own page. When the user is on a page, I want them to be able to add a report to their favourites. I don't mean browser favourites, I mean their favourite reports when they log into the system

Googling this, for obvious reasons, brings back endless tutorials/scripts on how to add to the browser favourites which isn't what I want

I have a button saying "Add to Favourites". When this is clicked, the report should be added. The button should then be removed and replaced with one saying "Remove From Favourite"

I realise ASP/PHP will be needed to do the actual adding/removing but any guidance on how to achieve this would be most helpful.

Would it be something along the lines of

$(function() {
  $('.report_add').click(function() {
    this_id= this.attr("id");
    $.ajax({
      type: 'POST',
      data: 'reportid'+this_id+'=&userid=789',
      success: function() { ... },
      error: function(){ ... },
      url: '/url/',
      cache:false
    });
  });
});

Solution

  • You can change this:

    this_id= this.attr("id");
    
    data: 'reportid'+this_id+'=&userid=789',
    

    to this:

    var this_id= this.id;
    
    data: 'reportid='+this_id+'&userid=789',
    

    or:

    var this_id= $(this).attr("id"); // add a jQuery wrapper
    
    data: 'reportid='+this_id+'&userid=789',
    

    In your code you have two issues

    1. you are not picking the id correctly because you applied jQuery's .attr() method to a dom node instead of jQuery object. so that has to be either this.id or $(this).attr('id').

    2. your data string is not well formed:

    data: 'reportid'+this_id+'=&userid=789',
    //-------------^----------^--------------your '=' sign is at wrong place
    

    instead you can send the values like this:

     data: 'reportid='+this_id+'&userid=789',
    

    or

    data: {reportid : this_id, userid : 789},
    

    in your code:

    $(function() {
       $('.report_add').click(function() {
         var this_id= this.id; // <---------update this
         $.ajax({
            type: 'POST',
            data: {reportid : this_id, userid : 789}, // <---- and this
            success: function() { ... },
            error: function(){ ... },
            url: '/url/',
            cache:false
         });
      });
    });