"Enhance your experience by multiplying items with just a click on a designated list item + using

I am facing a major issue that I can't seem to resolve. I am using Leaflet to display a map combined with AJAX. When I click on a country, a list of "customers" is displayed. However, when I click on a specific customer for more information, the customer data multiplies exponentially (1 to 3 to 5 to 8...). Any assistance would be greatly appreciated.

var info = L.control();
    info.onAdd = function (map) {
        this._div = L.DomUtil.create('div', 'info'); 
        this._div.setAttribute("id", "idBoxList");

        L.DomEvent
        .addListener(this._div, 'mouseover', function () {
            MapShowCommand(); 
        });     

        this.update();
        this.clickPays();
        return this._div;
    };
  info.update = function (props) {
        this._div.innerHTML = '<div class="wrapper--popup-agents"><h3 class="title-med">Agents disponibles</h3><div class="buttonListeAgent" id="buttonListeAgentId"><span class="icon-keyboard_arrow_down"></span></div><div class="textfield">Liste des agents disponibles selon le pays sélectionné.</div></div><div class="agents--wrapper"><div class="content"><ul class="listAgents"></ul></div></div>';
    };
function MapShowCommand() {
        $('.buttonListeAgent').on('click', function(){
            if ($('#idBoxList').hasClass("show")) {
                $('#idBoxList').removeClass("show");
                info.update();
            }
        });

        $('.listAgents li').on('click', function(){
            var el = document.getElementById('overlayMap');
            L.DomEvent.disableScrollPropagation(el);
            L.DomEvent.disableClickPropagation(el); 

            var idAgent = $(this).children('input').val();
            var base_path = $('#url_base').val();
            console.log(idAgent);

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $.ajax({
                url:"/map-agents/agents",
                type:'POST',
                data:{idAgent:idAgent},
                dataType: "JSON",
                beforeSend: function () { 
                    $('.wrapper--agent-map').append('<div class="spinner-border text-info" role="status"></div>');
                },
                success: function (response) {  
                    console.log(response.nameFirm);
                    //$('.wrapper--agent-map').append('<div>'+ response.nameFirm +'</div>' + '<div>'+ response.country +'</div>' +'<div>'+ response.city +'</div>' +'<div>'+ response.network +'</div>' + '<div>'+ response.lastName +'</div>');
                },
                complete: function () {
                    $('.spinner-border.text-info').remove();
                },
                error: function (response){
                    console.log(response);
                }
            });
        });

Image displaying errors:

https://i.sstatic.net/vbNBV.png

Answer №1

Ensure that you do not repeatedly attach click event listeners to elements on mouseover by utilizing the .off() method.

$('.buttonListeAgent').off().on('click', function(){
...

$('.listAgents li').off().on('click', function(){
...

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

The link function fails to execute

I have created a custom Directive. The issue I am facing is that the html template is not being rendered. Upon debugging, I noticed that the link function is never called because the instance function is also never called. To troubleshoot, I added "debu ...

How to Use jQuery to Detect Audio Position in HTML

Is it possible to use the HTML5 Audio tag with an eventListener or action using Dom/jQuery to trigger an event during playback or at the end? This answer mentions currentTime but lacks examples. Pseudo code provided below. <!DOCTYPE html> <html& ...

The response from getStaticProps in Next.js is not valid

While following the Next.js documentation, I attempted to retrieve data from a local server but encountered an error message: FetchError: invalid json response body at http://localhost:3000/agency/all reason: Unexpected token < in JSON at position 0 ...

Discrepancy in date formatting between development and production builds in Next.js

Looking for some assistance with my issue. Initially, when I retrieve the API from my local development environment, the output matches my expectations. It displays details such as my current location and timezone. / 20230713184522 // http://localhost:300 ...

Determine which scroll bar is currently in use

I'm running into an issue with multiple scrollbars on my page - they just don't seem to be functioning correctly: <div class="dates-container" v-for="id in ids"> <overlay-scrollbars :ref="`datesHeader` ...

Solving compatibility problems with jquery AJAX requests on multiple browsers

searchCompanyExecutives: function(criteria, callback) { var params = $j.extend({ type: "GET", data: criteria, url: "/wa/rs/company_executives?random=" + Math.floor(Math.random() * (new Date()).getTime() + 1), ...

Error: Validation error encountered while validating recipe: _listId field is mandatory and must be provided

As a newcomer to node.js, I am attempting to create a cookbook restful API using nodejs. The goal is to have a list of recipes where each recipe is associated with a specific list selected by its id. However, I am encountering an issue while trying to retr ...

Showing the result of a backend script on the current page using PHP

I currently have a PHP web application that involves submitting data to a backend pipeline, also written in PHP. This pipeline consists of an external script that my application accesses using the 'exec' PHP function. The pipeline follows a multi ...

Angular 2 encountering a memory exhaustion issue in the JavaScript heap

I am currently using Angular CLI and would appreciate it if you could verify my CLI information @angular/cli: 1.2.1 node: 6.10.0 os: win32 x64 @angular/animations: 4.1.1 @angular/common: 4.0.0 @angular/compiler: 4.0.0 @angular/compiler-cli: 4.0.0 @angular ...

Instructions on utilizing API call ( jssor_slider1.$GoTo(N))

Hi there, I could use some assistance with using the Api Call. I've been attempting to specify a slide using a command, but nothing seems to be working. Sorry for my inexperience, I appreciate your patience. Thank you! <script> function toSli ...

Tips for effectively retrieving data from the server in Node.js

When attempting to retrieve data using /data with server-side fetch, I encountered the following errors: response.getCategory is not a function (()=>{ const url = "/data"; fetch(url) .then(response => { console ...

Tips for obtaining Jquery Ajax Readystates

Is there a way to determine the readystate of an ajax request using jQuery? Typically, without the use of jQuery, we would send an ajax request like this: http.open("POST", url, true); http.onreadystatechange = function() { if(http.readyState == 4 & ...

When clicking in JavaScript, there are two parts to the function, however only one part will work at any given time

I am currently working with two server-side PHP scripts: 1. /addit.php - which generates a PDF file on the server based on the provided ID 2. /viewit.php - which allows the PDF file to be downloaded to the browser window. While both of these scripts are ...

The outer DIV will envelop and grow taller in conjunction with the inner DIV

Could use a little help here. Thank you :) I'm having trouble figuring out how to get the outer div to wrap around the inner div and expand upwards with the content inside the inner editable div. The inner div should expand from bottom to top, and t ...

What are some methods for extracting a value from a separate webpage and saving it as a variable in my code?

I am utilizing graphite to obtain statistics and would like to display a justgage gauge for a specific variable. Graphite provides values in either JSON format: [{"target": "snmp.ssbSubstation.realEnergy.1", "datapoints": [[4511552439.0, 1417540920]]}] o ...

Encountered an issue with md-autocomplete: Attempting to read property 'success' of an undefined element

I encountered an issue while using Material Angular framework and md-autocomplete. The error message I receive is: Cannot read property 'success' of undefined. Below is the snippet of my code: /*My app.js*/ var app = angular.module('app&apo ...

What could be causing my jQuery AJAX request to a Django view to consistently trigger the error callback function?

Here is an example of my jQuery code: $.ajax({ url:"/process_values/", type: "POST", data: {values:['1','2']}, success:function(response){ alert("success: " + response); }, error:function (xhr, textStatu ...

Determine the availability of a distant website through AJAX requests

My website runs PHP's cURL to check the online status of 5 different URLs, however, this process tends to slow down the page load time significantly, especially if one of the sites being checked is not working. Someone suggested using jQuery's a ...

AJAX requests are causing an issue by inserting an extra line break in

My dropdown menu is structured like this: <select class="quick-drop" id="block-type-drop"> <option value="Block">Block</option> <option value="Monthly">Monthly</option> <option value="Weekly">Weekly</option> ...

Trigger a function in JavaScript/jQuery after an event has finished executing and has provided a return value

Is there a way in JavaScript/jQuery to execute a function after all callback handlers following a keyDown event have finished? I have noticed that checking the value of a form input box immediately after the keyDown event returns an empty value, but when I ...