The issue of a non-firing Ajax click event in a JavaScript file

I have set up a table in JSP and am attempting to trigger a function when clicking on the table rows to post the data. I created a JavaScript file with an ajax click event, but unfortunately, the event is not being fired.

    $(document).ready(function() {
    $(document).on("click",'.outi',(function(MyObj)
    {   var Myjson = JSON.stringify(MyObj); 
         $.ajax({
             // POST Method
             method: "POST",
             // URL
             url: "Client_frameServlet",
             // Asynchronous mode to wait for the end of the ajax before continuing
             async: false, // Synchronous mode
             // Sending data
             data: Myjson ,
             dataType: "json" ,
             success: function() {
            alert('In Ajax');
        }
             
         })
    }));
    });
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html>
    <META HTTP-EQUIV="expires" CONTENT="0">
    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <META http-equiv="Content-Type" content="text/html; charset="iso-8859-1">
    <head>
      <title>TX06</title>
      <link rel='stylesheet' type='text/css' href='style.css'>
      <script src="date.js"></SCRIPT>
    </head>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"
               ></script>
    <script src="res_gen.js">
    
    </script>
    <body>
     
      <table width="100%" align="center" border=0 cellspacing="0" cellpadding="0">
        <tr>
          <td>
              <table width="95%" align="center" border=0 cellspacing="0" cellpadding="0">
                <tr>
                  <td class="titre">Résultat de la recherche</td>
                </tr>
              </table>
          </td>
        </tr>
      </table>
    <br>
    <table border=0 bgcolor=#92ADC2 cellspacing=1 cellpadding=3 width=95% align=center>
        <tr class=entete>
            <td class=texte8 align=center>&nbsp;Nom</td>
            <td class=texte8 align=center>&nbsp;Date de naissance</td>
            <td class=texte8 align=center>&nbsp;Coll</td>
            <td class=texte8 align=center>&nbsp;Numéro</td>
            <td class=texte8 align=center>&nbsp;Numéro contact</td>     
            <td class=texte8 align=center>&nbsp;TITULAIRE</td>
        </tr>
        
                <tr class="outi" onMouseOver="this.className='over';" onMouseOut="this.className='outi';">
                    <td class=texte7 align=left colspan=5>&nbsp;Aucun client ne trouve</td>
                </tr>
            
    </table>
    
    <br>
    <table width="95%" align="center" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td align="right">
            <a target="corps" href="gen_rech.jsp" class="rub2" onmouseover="voltar.src = '../images/fr/voltar_s.gif';" onmouseout="voltar.src = '../images/fr/voltar.gif';"><img src="../images/fr/voltar.gif" border="0" name=voltar ></a>
        </td>
      </tr> 
    </table>
    </body>
    </html>

PS: I have attempted calling by classname without success and have verified browser parameters to confirm that the event is indeed not being triggered.

Answer №1

Take note of the element(s) you're targeting in your click handler:

$(document).on("click", '.outi', (function(MyObj){

The click handler function will only run for elements with the outi class. However, your element does not actually possess that class.

It initially has the class when the page loads:

<tr class="outi" onMouseOver="this.className='over';" onMouseOut="this.className='outi';">

But pay attention to what the inline JavaScript on that element is doing. It changes the class when the mouse hovers over it.

The mouse will hover over the element before the user clicks on it.

You should target the actual class it currently has:

$(document).ready(function() {
  $(document).on("click", '.over', (function(MyObj){
    console.log('test');
  }));
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<table border=0 bgcolor=#92ADC2 cellspacing=1 cellpadding=3 width=95% align=center>
  <tr class=entete>
    <td class=texte8 align=center>&nbsp;Nom</td>
    <td class=texte8 align=center>&nbsp;Date de naissance</td>
    <td class=texte8 align=center>&nbsp;Collaborateur</td>
    <td class=texte8 align=center>&nbsp;Numéro de la carte</td>
    <td class=texte8 align=center>&nbsp;Numéro de contrat</td>      
    <td class=texte8 align=center>&nbsp;TITULAIRE</td>
  </tr>
  <tr class="outi" onMouseOver="this.className='over';" onMouseOut="this.className='outi';">
    <td class=texte7 align=left colspan=5>&nbsp;Aucun client ne trouve</td>
  </tr>
</table>

Alternatively, consider using both classes instead of replacing one with the other:

$(document).ready(function() {
  $(document).on("click", '.outi', (function(MyObj){
    console.log('test');
  }));
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<table border=0 bgcolor=#92ADC2 cellspacing=1 cellpadding=3 width=95% align=center>
  <tr class=entete>
    <td class=texte8 align=center>&nbsp;Nom</td>
    <td class=texte8 align=center>&nbsp;Date de naissance</td>
    <td class=texte8 align=center>&nbsp;Collaborateur</td>
    <td class=texte8 align=center>&nbsp;Numéro de la carte</td>
    <td class=texte8 align=center>&nbsp;Numéro de contrat</td>      
    <td class=texte8 align=center>&nbsp;TITULAIRE</td>
  </tr>
  <tr class="outi" onMouseOver="this.classList.add('over');" onMouseOut="this.classList.remove('over');">
    <td class=texte7 align=left colspan=5>&nbsp;Aucun client ne trouve</td>
  </tr>
</table>

Regardless of your approach, the key point is that when filtering based on a specific class, the element must have that class to trigger the event handler.

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

Developing clickable hyperlinks within a jQuery Datatable

I am currently in the process of transitioning from an asp.net GridView Control to a jQuery DataTable with Ajax. On my project's home page, I have a visually appealing image grid that is justified. Each image in this grid acts as a link, redirecting u ...

In Vue.js, modifying a parent component variable using $parent does not update the interpolation syntax

Child component <template> <div> <h3>Child Component</h3> <div> <button @click="changeValue()">Update Parent Value</button> </div> </div> </template> <script> export ...

Swap out the hyperlink text for a dropdown menu when clicked and then revert back

Is there a way to dynamically switch between a label/text and a Kendo Combobox in a div using JavaScript when clicking on the text? The desired functionality includes: Clicking on the text displays the combobox, clicking away from it hides the combobox a ...

Using the onreadystatechange method is the preferred way to activate a XMLHttpRequest, as I am unable to trigger it using other methods

I have a table in my HTML that contains names, and I want to implement a feature where clicking on a name will trigger an 'Alert' popup with additional details about the person. To achieve this, I am planning to use XMLHttpRequest to send the nam ...

Having trouble showing image on an Android app using JSON parser from a webpage

Recently, I started working on Android development and am currently dealing with parsing web page data using JSON. I followed the androidhive JSON parser tutorial and was able to successfully parse the title but faced difficulties with parsing the image. D ...

Navigate to a different XML page in Android upon clicking a button

In my Eclipse project, I have two layout files: activity_main.xml and activity_main2.xml. I attempted to create a button in activity_main.xml that, when clicked, would navigate to the screen of activity_main2.xml. Within com.example.myfirstapp, I have the ...

Node.js: Managing multiple occurrences of the same event name for testing purposes

When it comes to unit testing using mocha, I am looking for a way to set up an asynchronous queue for handling events. Previously, I used a once() Promise to wait for events like this: import EventEmitter from 'events' import { once } from ' ...

Converting Milliseconds to a Date using JavaScript

I have been facing a challenge with converting milliseconds data into date format. Despite trying various methods, I found that the solution provided in this link only works for a limited range of milliseconds values and fails for higher values. My goal is ...

Upgrading Table Models with ASP.NET MVC 3 and Ajax

Trying to update a record list using ajax, displayed in a table where each record has a JavaScript delete link. When I load the table initially, the RemoveLink functions correctly. However, once the div "RecordListPartialView" is updated via ajax, it stops ...

Displaying Image from Jquery Ajax Response

I have a PHP script that can resize images with specified dimensions by passing the width and height as variables like so: resize.php?width=100&height=200. The content-type of this PHP script is set to image/jpg. Additionally, I have an HTML page wher ...

Is Node.js and Express a suitable server-side package for a WebGL web application?

Currently, I am in the process of creating a webgl application. While using mongoDB for my database and three.js as my webgl library has been helpful during development, I find myself unsure about which server-side technology to incorporate into the appl ...

HTML-Formatted Email Content

Similar Question: MailTo with HTML body I am looking to utilize JavaScript to send emails. I came across this helpful post: Sending emails with JavaScript. My goal is to include images, bold text, and color changes in the email content. Does anyone h ...

Ways to display tinyMCE content in a unique manner

I've been diving into node.js/express/mongoDB and decided to create a blog. I encountered an issue with rendering the content inputted through tinyMCE as HTML - instead, it's displaying the tags around my content. How can I properly display it as ...

Adjusting the viewer.js script

In order to view my pdf files using Mozilla's pdfjs plugin, I currently pass a query parameter to viewer.html like this: http://localhost/MyProject/viewer.html/?file=file.pdf Although this method works fine for me, I have a unique requirement for my ...

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: The specified column 'Knight' is not recognized in the provided field list

I can't seem to figure out why this issue is occurring when the rest of my code that uses MySQL is functioning flawlessly. The problem arises only when I attempt to set a string value. Here is the MySQLManager class: http://pastebin.com/RWavasPh I ...

What is the best way to execute a function individually for every tag within a vue.js application?

I'm currently exploring the world of Vue JS and I thought it would be interesting to experiment with something new. Sometimes looking at the code first makes understanding it much easier than a lengthy explanation. Check out this code snippet on jsFi ...

Using Express in Node.js to send a GET request to a different server from a Node route

When a client triggers a GET request by clicking a button on the index page, it sends data to a route that is configured like this: app.js var route = require('./routes/index'); var button = require('./routes/button'); app.use('/ ...

Update the object with fresh data once the XML data is transformed into JSON format

I am currently converting XML attributes into JSON format. Below is the complete function that I will explain step by step: request.execute('[someSP].[spSomeSP]', function(err, dataset) { if (err) { reject(err); } ...

The route param is throwing a "Cannot read property 'name' of undefined" error, indicating that the property

Currently, I am enrolled in an ExpressJS course on TUTS+ From the video tutorial, I have implemented the following code snippet (excerpt from video): var express = require('express'), app = express(); app.get('/name/:name', funct ...

"Improving User Experience with React.js Serverside Rendering and Interactive Event Handling

Currently, I am in the process of learning how to utilize react.js but I am facing some challenges with using event handlers. Here's a question that has been lingering in my mind: Is it feasible to employ server-side rendering and automatically send e ...