Guide on connecting JavaScript to a Font Awesome icon

I added a fontawesome icon to my HTML as a button and now I want to use JavaScript to trigger it AJAX style

<a href="#"><i id="heart" class="jam jam-heart-f"></i> Like</a>

Below is the JavaScript code I attempted to use to trigger it, but I haven't encountered any errors. My goal is to post the 'like' attempt to a PHP page called like.php in order to add the link to a database.

$(document).ready(function()
{

$('body').on("click",'#heart',function()
{
    var videoId = "<?php echo $video_id; ?>";


    var A=$(this).attr("id");
    var B=A.split("like");
    var messageID=B[1];
    var C=parseInt($("#likeCount"+messageID).html());


       $.ajax({
    method: 'POST',
    url: 'like.php',
    data: {videoId: videoId},
    cache: false,
        success: function(result){
            likeInfo = JSON.parse(result);
                    $("#likeCount1").html("Likes:" + likeInfo.likeCount);

            //document.getElementById("likeCount1").value = likeInfo.likeCount;
            //$("#likeCount1").html(likeCount);
        }

        }); 



    }


});

Despite setting #heart as the target in JS using the id="heart" with the font awesome icon, it doesn't seem to be triggered. Any suggestions on how I can solve this issue?

Answer №1

Don't forget to include the closing parenthesis and semicolon in your $('body').on... statement

Here's a corrected version:

$(document).ready(function()
{

    $('body').on("click",'#heart',function()
    {
        var videoId = "<?php echo $video_id; ?>";


        var A=$(this).attr("id");
        var B=A.split("like");
        var messageID=B[1];
        var C=parseInt($("#likeCount"+messageID).html());


           $.ajax({
        method: 'POST',
        url: 'like.php',
        data: {videoId: videoId},
        cache: false,
            success: function(result){
                likeInfo = JSON.parse(result);
                        $("#likeCount1").html("Likes:" + likeInfo.likeCount);

            //document.getElementById("likeCount1").value = likeInfo.likeCount;
            //$("#likeCount1").html(likeCount);
            }
        }); 
    });
});

Answer №2

Your code successfully triggers the post-request, however, there seems to be an issue with closing your functions and scopes properly.

I tested it out on this JSFiddle link for reference.

Here is the revised code snippet to ensure compatibility with StackOverflow:

$(document).ready(function() {

      $('body').on("click", '#heart', function() {
          var videoId = "<?php echo $video_id; ?>";

          var A = $(this).attr("id");
          var B = A.split("like");
          var messageID = B[1];
          var C = parseInt($("#likeCount" + messageID).html());

          $.ajax({
            method: 'POST',
            url: 'like.php',
            data: {
              videoId: videoId
            },
            cache: false,
            success: function(result) {
              likeInfo = JSON.parse(result);
              $("#likeCount1").html("Likes:" + likeInfo.likeCount);
            }
          });
      });
});

Furthermore, there appears to be a syntax error indicated as

Uncaught SyntaxError: missing ) after argument list
in your JavaScript console. Please check the network tab to monitor outgoing requests for accurate data transmission by clicking the heart button.

We recommend using an advanced js editor such as VS Code for error detection before running the code. It's a free, lightweight, and comprehensive tool for developers.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for eliminating the chat value from an array tab in React

tabs: [ '/home', '/about', '/chat' ]; <ResponsiveNav ppearance="subtle" justified removable moreText={<Icon icon="more" />} moreProps={{ noCar ...

Capture Your Scene with Three.js

I am facing an issue where I need to capture a screenshot of a website. I have tried using html2canvas and it is working fine. However, the problem arises because I am using both THREE.WebGLRenderer and THREE.CSS3DRenderer (for HTML in webGL). The screen ...

Angular, perplexed by the output displayed in the console

I'm completely new to Angular and feeling a bit lost when it comes to the console output of an Angular app. Let me show you what I've been working on so far! app.component.ts import { Component } from '@angular/core'; @Component({ ...

Effortlessly apply CSS styles to multiple cached jQuery variables without redundancy

Hey there, I've got this piece of code written in Javascript for a classic ASP page. Since there are no CSS classes defined, everything is handled within the Javascript itself. var $a= $('#a'), $v= $('#v'), $s= $('#s'), ...

Is there a specific perl regular expression that can accurately identify a javascript associative array?

Looking for a way to parse JavaScript code using Perl? var materials ={ foo: "bar", bar: "baz", baz: "foo" }, If you have the JavaScript variable as a string and need to extract the associative array's body for JSON parsing in Perl, you ...

Increase the size of the SVG area

I'm still learning how to work with SVGs, so I appreciate your patience as I ask what may seem like a simple question. Currently, I have an SVG image that resembles a cake shape. See it here: https://i.sstatic.net/tDhUL.png Take a look at the code: ...

Legend alignment issue in Firefox disrupting Flexbox functionality

My fieldset has a legend containing text and a button. I am attempting to use flexbox to right-align the button within the legend. This setup works correctly in Chrome, but encounters issues in Firefox. I have managed to replicate the problem with a simpl ...

Navigating through the browser history will allow you to view the

Currently, I am working on the localhost/mysite/users page. This page displays a list of users that is fetched through an ajax request. However, I have encountered a strange issue. Whenever I navigate back and then forward again, the content on the localh ...

The database powered by Postgresql performs flawlessly when it comes to updating data with accurate code execution. However, there seems to be an

Imagine a zoo with a postgresql database. To enable web access to this database, I am using php and javascript. Most of the web pages are working fine, but I am currently working on a page where clients can add or remove animals from existing exhibits. T ...

What is the significance of AngularJS in crafting Single Page Applications?

My introduction to AngularJS was discovering its perfection for Single Page Applications (SPAs). I'm intrigued by what this means and eager to learn more about it. Can someone explain the significance of SPAs in relation to AngularJS? ...

What is the best way to establish a connection between a client and MongoDB

My attempt to connect my client with MongoDB resulted in an error message: MongoParseError: option useunifedtopology is not supported. I am unsure of the reason behind this issue and would greatly appreciate your assistance. Below is the snippet of code ...

"Click-to-Submit Button Triggering Error Notification before Redirecting to New Page

I am looking to implement an error message for a button and then redirect the user to a specific URL. However, I am unsure of how to achieve this using JQuery as I am relatively new to it. The idea is that the user uploads a file and then clicks on the Sub ...

The transparency of the navigation menu is perplexing to me. I am unclear as to the reasoning behind it. I desire a

I am currently using a pre-made WordPress theme. Recently, I incorporated particles.js as the background for my website. The issue I am facing now is that my navigation menu is blending into the same color as the background. I have tried defining a separat ...

Ways to insert a gap underneath every line

Hello, I'm struggling to create space below each line of code. I've tried using the br tag and margin property, but it didn't work. Can anyone help me with this? I'm not sure if the current HTML structure is correct or if I should swit ...

HTML - Image is only partially visible

While attempting to set up this theme for my blog, I encountered a minor issue - the avatars in the comment section are not displaying correctly, as they appear to be cut off along with the container. Despite numerous attempts to edit the code, I have be ...

Issue with JQuery mobile: dynamically inserted popup fails to appear

Can you help me troubleshoot an issue with my function? It's supposed to take a text string and output the text surrounded by '¬¬¬' in a button with a pop-up menu attached. The button looks fine, but when clicked, the popup ul list doesn& ...

Embed API requests using JavaScript's Axios library to ensure the correct promise is returned

I am currently facing an issue with posting data to my API using axios. In order to make the request, I need to include a XSFR-token along with it. The technologies I am using for this are React, Redux, Thunk, and Axios. The problem lies in handling this ...

Does GIF animation operate on the same thread as JavaScript in all popular web browsers?

When my AJAX request is in progress, an animated GIF is displayed to show activity. However, I have noticed that the animation freezes while the response from the request is being processed by a script that heavily updates the DOM. After researching this ...

Wordpress causing Jquery to malfunction; PHP function not executing

Looking to incorporate a script into my WordPress function.php file. Here's what I have so far: <?php function add_google_jquery() { if ( !is_admin() ) { wp_deregister_script('jquery'); wp_register_script('jquery', ...

Freemarker substitute & and &ampersand;

I am facing an issue with Freemarker. I need to eliminate all the special characters from this sentence as well as from similar sentences in the future: BLA BLA RANDOM &, RANDOM BLA In particular, I want to remove the & character. The platform ...