Executing JavaScript function by clicking on <img>

I've been developing a website similar to YouTube, and I'm facing difficulties with the Like/Dislike feature for comments.

Currently, I have implemented it in the following way: when a user clicks on an image (thumbsUp.png or thumbsDown.png), a JavaScript function is called. Below is the PHP code snippet where $enregistrement represents the comment:

$block .='<img src="'.APP_IMG_PATH.'thumbsup.png" onclick="javascript:addLike('.$enregistrement["Comm_ID"].')" style="width:20px;height:20px"></img>  '.$enregistrement["Likes"].'  '
       . '<img src="'.APP_IMG_PATH.'thumbsdown.png" onclick="javascript:addDislike('.$enregistrement["Comm_ID"].')" style="width:20px;height:20px"></img>'.$enregistrement["Dislikes"].'';

Here are my JavaScript functions:

$block .='
<script>
function addlike(idCo){
    $.ajax({
        type: "GET",
        url: "'.APP_SERVICE_PATH.'SetComment.php",
        data: {Like:1, commID:idCo},
        success: function(data){
        },
        error: function(exc){
              alert("Exception: Une erreur a été levé sur $_GET de addLike(). " + exc);
        }
   )};
}
                    
function addDislike(idCo){
    $.ajax({
       type: "GET",
       url: "'.APP_SERVICE_PATH.'SetComment.php",
       data: {Dislike:1, commID:idCo},
       success: function(data){
       },
       error: function(exc){
           alert("Exception: Une erreur a été levé sur $_GET de addDislike().");
       }
  )};
}
</script>';

However, I'm having an issue where the onclick event is not triggering at all! Previously, I had <a href=""> tags surrounding the <img> tags which worked but caused page reloads upon each click, something I want to avoid.

If anyone can spot what I might be doing wrong, I would greatly appreciate any assistance.

Please note that I am aware of the need to separate PHP and HTML code, so please refrain from commenting on this aspect. Thank you!

Answer №1

Your code has several issues that need to be addressed. Firstly, the

onclick="javascript:addLike('.$enregistrement["Comm_ID"].')"
function is self-invoking and should not have parenthesis for correct registration.

Make sure to wrap your images with

<a data-id="'.$enregistrement["Comm_ID"].'"></a>
and then modify your function as follows:

function addDislike(event) {
    // Prevent default behavior of following the link
    event.preventDefault();

    var idCo = this.dataset.id;
    // or var idCo = $(this).data("id");

    $.ajax({
        type: "GET",
        url: "'.APP_SERVICE_PATH.'SetComment.php",
        data: {Dislike:1, commID:idCo},
        success: function(data){
        },
        error: function(exc){
        alert("Exception: An error occurred on $_GET in addDislike().");
   }

}

Answer №2

My error was discovered: I mistakenly opened the Ajax function with $.ajax({ and closed it incorrectly as }; instead of });

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

Why does my dialog box only open the first time and not the second time?

I have created my own custom dialog box using jQuery and it seems to be working fine initially. However, after closing it once, when I try to open it again nothing appears. Can anyone help me identify what's causing this issue? Below is the source co ...

Transforming AJAX into jQuery

How can I rewrite the following code using only the jQuery library? <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> function do_it(value) { var url = "test.p ...

How to add a background image in CSS with HTML's help

I am a beginner learning HTML and CSS, attempting to incorporate a Full Screen Background Image using CSS. Unfortunately, the code I have written is not working as expected despite following various tutorials. Below is my code: HTML file <!DOCTYPE htm ...

Is it possible to execute a function when the AJAX request is successful and returns a status code of

I am looking to implement the success function to only run a certain function if the status code is 200. I have come across this example: $.ajax ({ success: function(data,textStatus,jqXHR){ external(); } )}; However, I have not found a clear ...

Encountered a Next-Auth Error: Unable to fetch data, TypeError: fetch failed within

I've been struggling with a unique issue that I haven't found a solution for in any other forum. My Configuration NextJS: v13.0.3 NextAuth: v4.16.4 npm: v8.19.2 node: v18.12.1 When the Issue Arises This particular error only occurs in the pr ...

Swapping out bullet points for delicious food icons in an unordered list on an HTML page

I am working with the following code snippet: <div id="instructions"> <h3>Get it done</h3> <ol> <li>In a blender add the eggs, chocolate powder, butter, flour, sugar and milk.</li> <li>Then whisk ...

Tips for converting a string to RAW data type in Oracle using PHP

Currently struggling with sending lengthy strings to Oracle stored procedure RAW variable, encountering the following error: oci_execute(): ORA-06502: PL/SQL: numeric or value error In need of assistance on converting a String to Raw datatype. ...

How can I open a PDF file on the frontend using the Django framework?

I am attempting to extract content from a PDF file using the Django framework. Here is what I have tried so far: def upload(request): try: if request.method == 'POST': if request.FILES['document'].name.split ...

Trouble with Sound during Quickblox Webrtc Audio Calls

I am having an issue with my audio calls. When I make a call to another user, everything seems fine except that I cannot hear any sound when speaking into the microphone. I am only interested in making audio calls. The call is initiated by pressing a butt ...

Adding an extra element to the <MuiThemeProvider /> causes the page to display as blank with no error notifications

After incorporating Material UI into my Meteor application via npm install --save material ui I successfully implemented the <Header /> component in my app.js file. However, when I try to add additional components, such as localhost:3000, all I see ...

Creating temp files in PHP for storing images is a common task. In this

Is there a way to save a logo to a Tmp File and adjust the paper Size, Margin, and Position on the Tmp File when creating an invoice print? I found this code in an article that works for printing, but I'm unsure how the writing process functions. Can ...

Reorganizing asynchronous code into a nested synchronous structure in Meteor/React

Recently, I've been experimenting with running data fetching code in a container component and passing it to the display component in order to streamline my use of hooks and reduce load time. I've tested both await/sync and Meteor's wrapAsyn ...

Creating dual permission menus for two different roles in Vue JS 3

This is my router file checking which role is logged in: router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAdmin)) { if(VueJwtDecode.decode(localStorage.getItem('accessToken')).sub == &quo ...

Emphasis and dimension of form

I need help with a field that is supposed to have a black outline, similar to the one shown below: However, here is what I currently have in my code: .r{ height: 40px; font-size: 30px; width: 100px; font-family: 'proxima_novalight ...

Ensuring smooth video playback on a website

My website is experiencing issues due to a large mov file that's 157 megabytes. When I try to run it on my page using a javascript scroller animation, the animation becomes choppy. Additionally, I used css to simulate a mask, but it doesn't get m ...

Obtain the object literal string with additional decorative strings surrounding it

In my current Typescript code, I have an object literal structured like this: const MyNamesStrings = { a: { b: "hello", c: "bye" } d: { e: "qwerty" } } However, I am looking for a way to wrap these strings with add ...

The process of implementing server-side rendering for React Next applications with Material-ui using CSS

I have developed a basic React application using Next.js with an integrated express server: app.prepare() .then(() => { const server = express() server.get('/job/:id', (req, res) => { const actualPage = '/job' const ...

Node.js is throwing an error code 344, indicating that it is not possible to manipulate headers after they have already been

I'm still learning about Node and I've encountered this confusing error that I can't seem to figure out. I've searched for similar cases online, but none of them quite match mine. Any help would be greatly appreciated. From what I gathe ...

Failure to inherit props in child components when using React-Redux

I've been following a React-Redux tutorial and encountered an error in the first part of the section titled "React Redux tutorial: asynchronous actions in Redux, the naive way". Post.componentDidMount src/js/components/Posts.js:12 9 | ...

Is there a way to remove the excess white space beneath my content without resorting to using overflow-y: hidden?

I am struggling to eliminate the excess white space below the body of my web page in order to make it fit perfectly within the view of a web browser. Adding height helps with vertical alignment but leaves unwanted white space. I need a solution that doesn ...