I call ajax only once but ajax is called many times

I am trying to write some code to make a request when I click a button. When I click my button, multiple requests are being made, and I can’t figure out why this is happening.

Here is the code of the button in the blade file:

<div class="form-group">
    @if(!empty($textLesson))

    @php
    $text_id=$textLesson->id;
    $webinar_id=$webinar->id;
    $lessonAudio = App\Models\AudioAttachment::where('text_lesson_id',$text_id)->get();
    @endphp

    <div id="btnDiv">
        <x-panel.attach-audio-component :textid="$text_id" :webinarid="$webinar_id" :textLesson="$textLesson"
            :userLanguages="$userLanguages" />
    </div>
    @if(!empty($lessonAudio) and !$lessonAudio->isEmpty())

    <div id="audioListings">

      </div>
      

Here is the script where ajax is called:

<script>
    $(document).ready(function () {

        $('body').on('click', '#addAudio', function (e) {
            const $this = $(this);
            $textid = document.getElementById("addAudio").getAttribute("data-text-id");
            $webinarid = $this.attr('data-webinar-id');
            //alert($textid);
            e.preventDefault();
            let add_audio_modal = '<form id="addAudioFiles" method="post" action="/panel/text-lesson/saveaudio"  enctype= "multipart/form-data">';
            add_audio_modal += '@csrf';
            add_audio_modal += $('#audioFilesModal').html();
            add_audio_modal += '</div>';

            Swal.fire({
                html: add_audio_modal,
                showCancelButton: false,
                showConfirmButton: false,
                customClass: {
                    content: 'p-0 text-left',
                },
                width: '48rem',
            });
        });

        $('body').on('click', '#saveaudios', function (e) {
            e.preventDefault();

            const $this = $(this);
            let form = $('#addAudioFiles');

            let formData = new FormData(form[0]);
            formData.append('webinar_id', $webinarid);
            formData.append('text_id', $textid);
            let action = form.attr('action');

            $this.addClass('loadingbar gray').prop('disabled', true);
            form.find('input').removeClass('is-invalid');
            form.find('textarea').removeClass('is-invalid');

            $.ajax({
                url: action,
                type: 'POST',
                data: formData, // use the FormData object as the data to be submitted
                processData: false, // prevent jQuery from processing the data
                contentType: false, // let the browser set the content type automatically
                success: function (result) {
                    if (result && result.code === 200) {

                       // do with result

                      
                    
                },
                error: function (err) {
                    // error handling code here
                  
                }
            });
        });
    });
</script>

i dont know why multiple requests are being made. please any one can help

>Solution :

This is because your $('body').on('click', '#saveaudios', function (e) {}); register click events multiple times. This might because of your script is loaded multiple times, event propagation or so on. So, you need to remove the previous event with off() event handler. So, your new code will looks as follows:

$('body').off('click', '#saveaudios').on('click', '#saveaudios', function(e) {
    // your ajax logic
});

Leave a Reply