Clicking multiple times triggers an ajax call, resulting in duplicated data being displayed

Whenever I click on the pop-up menu to select a customer, it pulls data using an ajax call and updates selections on a form. Everything is working fine, but if I click on .lookup-cust-hide again, the JSON data (customer list) duplicates itself. Now I end up with two full lists of customers combined...

I'm considering the need to somehow clear the ajax call at the end???

Javascript:

$("#customer .lookup-cust-hide").click(function() {
        $("#contactdiv1").css("display", "block");

        $.ajax({                                      
            url: 'customer_fill.php',                         
            data: {action:"invoice"},                                             
            dataType: 'json',                   
            success: function(data){
                populateSelectBoxes($('#contactdiv1 #dropdown'), data);

                function populateSelectBoxes($select, data) {
                    var customers = [];
                    $.each(data, function() {
                        customers.push('<li data-value="'+this.autonum+'">' + this.customer + '</li>');
                    });
                    $select.append(customers.join(''));
                }

                function populateTableRow($tableBody, data, selectedCustomerAutonum) {
                    var customers;
                    $.each(data, function() {
                        if (this.autonum == selectedCustomerAutonum) {
                            customers = this;
                            return false;
                        }
                    });
                    $($tableBody).val(customers.customer+ '\n' + customers.address1 + '\n' + customers.address2 + '\n' + customers.address3);
                }

                $('#contactdiv1 #dropdown li').click(function(e) {
                    var selection = $(this).attr("data-value");
                    $(this).parent().parent().parent().hide();
                    populateTableRow($('#customer-title'), data, selection);
                });


            }
        }); 
    });

    $("#contact #cancel").click(function() {
        $(this).parent().parent().hide();
    });

Answer №1

It was necessary to include the following code:

$("#contact #cancel").click(function() {
    $('ul').empty();
    $(this).parent().parent().hide();
});

Here are the final outcomes:

$("#customer .lookup-cust-hide").click(function() {
    $("#contactdiv1").css("display", "block");

    $.ajax({                                      
        url: 'customer_fill.php',                         
        data: {action:"invoice"},                                             
        dataType: 'json',                   
        success: function(data){
            populateSelectBoxes($('#contactdiv1 #dropdown'), data);

            function populateSelectBoxes($select, data) {
                var customers = [];
                $.each(data, function() {
                    customers.push('<li data-value="'+this.autonum+'">' + this.customer + '</li>');
                });
                $select.append(customers.join(''));
            }

            function populateTableRow($tableBody, data, selectedCustomerAutonum) {
                var customers;
                $.each(data, function() {
                    if (this.autonum == selectedCustomerAutonum) {
                        customers = this;
                        return false;
                    }
                });

                $($tableBody).val(customers.customer+ '\n' + customers.address1 + '\n' + customers.address2 + '\n' + customers.address3);
            }

            $('#contactdiv1 #dropdown li').click(function(e) {
                var selection = $(this).attr("data-value");
                $(this).parent().parent().parent().hide();
                populateTableRow($('#customer-title'), data, selection);
                $('ul').empty();
            });

        }
    }); 
});

$("#contact #cancel").click(function() {
    $('ul').empty();
    $(this).parent().parent().hide();
});

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

Using Filters in VueJs

I am currently working on creating a small Vue.js 2.0 application where I am utilizing the v-select component from here. The data format that I am dealing with looks something like this: { "model": [ { "id":1, ...

An error occurs in TypeScript when attempting to reduce a loop on an array

My array consists of objects structured like this type AnyType = { name: 'A' | 'B' | 'C'; isAny:boolean; }; const myArray :AnyType[] =[ {name:'A',isAny:true}, {name:'B',isAny:false}, ] I am trying ...

Is it possible to track the status of an audio download within Howler.js?

Currently, I am utilizing howler.js to incorporate audio playback on my website. However, since I am obtaining the audio files through direct links, the loading times vary based on the length of each audio track. Is there a method available to track the pr ...

Challenge encountered in Rails with Ajax altering image

I have a Ruby on Rails application and I've integrated the acts_as_votable gem for handling likes and unlikes. Users can like or unlike a post. I've implemented AJAX functionality to update the like count without refreshing the page, and it&apo ...

Implement automatic calculation by utilizing ajax to fetch values from the database whenever there is a change

I am completely lost on how to effectively make use of this. My initial thought is to implement JavaScript arrays. So, I have a select option available with values fetched from the database, and the select options are dynamic. By clicking on the "add row" ...

What is preventing me from accessing the variable?

Having some trouble using a variable from JSON in another function. Can someone lend a hand? async function fetchData() { let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d'); let data = await response.js ...

Ways to troubleshoot the error "push of undefined cannot be read" in Firebug Lite?

While attempting to open Firebug Lite for testing an AngularJS application in Chrome on OS X (Maverick), I encountered an issue. An error message appeared: cannot read property 'push' of undefined firebug-lite.js 30905 What steps can be taken t ...

Learn the technique for accessing array elements sequentially through setInterval with the help of jQuery and PHP

Below is the code from my index.php file: <html lang="en"> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function( ...

Component with Next.JS Server-Side Rendering

Is it possible to integrate a module into my project that only supports server side rendering? Here is the current project structure: index.js view.js part.js (Class component) Currently, I am able to use the module in the getServerSideProps method in ...

Pass data to JavaScript using Node.js Express server

I recently started learning nodejs and have encountered a challenge in sending a variable from my nodejs express server to a javascript file. The code I currently have is: res.send(String(playerLives)); The variable playerLives is an integer, and I faced ...

Default page featuring an AngularJS modal dialog displayed

I am attempting to display a modal popup dialog using an HTML template. However, instead of appearing as a popup dialog, the HTML code is being inserted into the default HTML page. I have included the controller used below. app.controller('sortFiles&a ...

Having multiple HTML select elements and utilizing jQuery AJAX

I am looking to implement a dynamic multiple select using AJAX and jQuery. The first select (c1) is functioning correctly. When I click on it, it triggers the appearance of another select (c2). Similarly, clicking on the second select (c2) should lead to ...

Exploring the right ID with jQuery

Within my HTML script, there are two forms structured like this: <form id="no1"> <input id="title" type="text" /> <input type="submit" /> </form> <form id="no2"> <input id="title" type="text" /> ...

Clicking on a href link inside a scrollable div-container causes it to malfunction, causing the page to jump

I have a draggable div container that contains dynamically generated content. In order to display this container, I use the following code: $( function() { $( "#dialog-message" ).dialog({ modal: true, height: 400, buttons: { Fertig: functi ...

Issue with a Django view not providing a return statement following an Ajax GET request

I am encountering an issue where the view function instruction is not executing after the Ajax GET request from the HTML page. Below is the content of model.py: from django.db import models from django.utils import timezone class user(models.Model): ...

Tips for refreshing a D3.js bubble chart with live JSON data updates

Currently delving into d3 and experimenting with transforming a static bubble chart into a dynamic one that adjusts by removing or adding bubbles based on JSON changes. I am aiming to have the JSON file refreshed every 5 seconds to update the bubble chart ...

The Angular ternary operator can be used in conjunction with functions for optimal

Consider this scenario: I have two functions that are triggered by a button click: <button ng-click="functionOne || functionTwo()"></button> However, I want to optimize this setup so that the functions are only called if they return a value. ...

Exploring the filter method in arrays to selectively print specific values of an object

const array = [ { value: "Value one", label: "Value at one" }, { value: "Value 2", label: "Value at 2" }, { value: "" , label: "Value at 3" } ...

The component encountered an error because the element type provided was not valid

I've encountered an error that has me stumped: https://i.sstatic.net/glSvr.png I've been trying to locate the HeaderSegment, but it seems to be missing from my project. I've checked for any imports, such as: import HeaderSegment from &apos ...

Issues with tracking changes in Vue.js when using reactive variables

After triggering a click event, I am attempting to choose a message from a json file. However, I am encountering an issue where the first click does not seem to select anything. Upon the second click, the selected messages are duplicated, and this pattern ...