Favorite button withXMLHttpRequest
<p>I have a link that if clicked or queried from the database to be true the icon displays a full heart and information is saved in the database like so:</p>

<pre><code>&lt;a id="fav"  href="#"&gt;&lt;i &lt;?if($fe == 1){?&gt;class="faved"&lt;?}else{?&gt;class="fav"&lt;?}?&gt;&gt;&lt;/i&gt;&lt;/a&gt;

$("#fav i.fav").click(function(){
                fav= new XMLHttpRequest();
                fav.open("GET", "http://test.php?u=&lt;?=$user_id?&gt;",  true);
                fav.send();
                $("#fav i").removeClass('fav').addClass('faved');
            });

            $("#fav i.faved").click(function(){
                fav= new XMLHttpRequest();
                fav.open("GET", "http://test.php?u=&lt;?=$user_id?&gt;",  true);
                fav.send();
                $("#fav i").removeClass('faved').addClass('fav');
            });
</code></pre>

<p>Currently it works great but the problem I am having is that if a user decides to un-favorite a page it either saves another record or tries to delete again depending on its current state. How do I get it to switch depending on the state. For instance if its not favorited, upon clicking it saves to the db and, without refreshing, click again it deletes from the db. </p>

<p><strong>UPDATE</strong></p>

<p>I also have actions in the links to tell my php to either delete or save a record. 
ex: <code>http://test.php?u=&lt;?=$user_id?&gt;a=1</code> (save) <code>http://test.php?u=&lt;?=$user_id?&gt;a=2</code> (delete)</p>

<p><strong>ANSWER</strong></p>

<p>Based off of @epascarello's answer. </p>

<pre><code>$("#fav").on("click", "i.fav", function(){
                var icon = $(this);
                var makeFavorite = icon.hasClass("fav");
                $.post("http://test.php&amp;u=&lt;?=$user_id?&gt;&amp;a=1",{isFav:makeFavorite}, function(){
                    icon.toggleClass("fav").toggleClass("faved");
                });
            });



$("#fav").on("click", "i.faved", function(){ 
            var icon = $(this);
            var delFavorite = icon.hasClass("faved");
            $.post("http://test.php&amp;u=&lt;?=$user_id?&gt;&amp;a=2",{isFav:delFavorite}, function(){
                icon.toggleClass("faved").toggleClass("fav");
            });   
        });
</code></pre>
