What is the reason for multiple ajax functions being triggered when submitting a form through ajax?

I have a Drupal form with an AJAX submit. Additionally, I have another jQuery $.get function that sends a request every 2 minutes and inserts the response into an HTML element. The form and this JavaScript code are independent of each other, performing separate tasks. However, upon submitting the AJAX form, I notice in the console that the $.get function is continuously called. I am unsure if this behavior is normal. How can I prevent this from happening?

Here is my form:

function example_my_form($form, &$form_state)
{

    $form['text'] = array(
        '#title' => t('Text'),
        '#type' => 'textarea',
        '#rows' => 5,
        '#default_value' => '',
        '#attributes' => array(
            'class' => array('form-control'),
            'placeholder' => drupal_strtolower(t('text'))
        ),
    );


    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Send',
        '#ajax' => array(
            'callback' => 'example_my_callback',
            'wrapper' => 'example_my_form',
            'method' => 'replace',
        )
    );


    return $form;

}

function example_my_callback(&$form, &$form_state) {
    return $form;
}

function example_my_form_submit(&$form, &$form_state) {
    /**
     * Perform desired actions
     */
}

And here is my JavaScript function:


    (function ($) {
        Drupal.behaviors.NoteRemind = {
            attach: function (context, settings) {
                function myFunction() {

                    var uid = Drupal.settings.MyModule.owneruid[0];
                    var note = document.getElementsByClassName('notecontainer')[0];
                    $.get('/rest/api/notes/' + uid, function (response, status, http) {
                        processNote(response);
                    }, 'json');

                    function processNote(response) {
                        var parsedData = JSON.parse(response);
                        console.log(parsedData);
                        /**
                         * Add parsed data to HTML element
                         */
                    }

                };


                myFunction();
                setInterval(function () {
                    myFunction();
                }, 120000);

            }
        };
    }(jQuery));

Answer №1

When it comes to Drupal behaviors, they are triggered not only on page load but also on every ajax response.
This behavior is intentional.
The value of the context variable passed to your behavior function will be either document during the initial load or the data received via ajax when an ajax request is made.
To ensure that setInterval is applied only once on the page, you can check if the context variable is equal to document or create your own variable to keep track of whether setInterval has been applied.

For example, checking the context:

if (context === document) {
  myFunction();
  setInterval(function () {
    myFunction();
  }, 120000);
}

Or setting your own variable:

if (typeof document.setAdded === 'undefined' || !document.setAdded) {
  myFunction();
  setInterval(function () {
    myFunction();
  }, 120000);
  document.setAdded = true;
}

If you don't need the extra function, you can simply use:

setInterval(myFunction, 120000);

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

I'm curious to know how this code is extracting parameters from the website URL. Can someone walk me through the process step by step?

I needed to extract parameters from a URL and started searching online for solutions. I came across a helpful link that provided the information I was looking for: After visiting the website, I found this code snippet: function getUrlVars() { var var ...

Javascript: Accessing a shared variable within the class

Embarking on my JavaScript programming journey filled me with optimism, but today I encountered a challenge that has left me stumped. Within my tutorial project, there exists a class named Model which contains both private and public variables. Of particu ...

What is the best method for retaining the complete YQL outcome within a JavaScript object?

I am trying to store the output of my YQL Query in a JavaScript object Here is my query: SELECT * FROM html WHERE url="http://myurl.com" and xpath="/html/body/center/table[1]/tr" Can someone guide me on how to proceed? I have gone through the YQL docu ...

"Implementing an Ajax request to loop through a JSON

I have received these results and now I want to display them in my view: val: {email: Array(1), first_name: Array(1)} email: Array(1) 0: "The email field is required." length: 1 __proto__: Array(0) first_name: Arra ...

Do all descendants consistently trigger rerenders?

Recently, I was exploring the React new documentation here, where I came across this interesting piece of information: The context value mentioned here is a JavaScript object with two properties, one being a function. Whenever MyApp re-renders (for examp ...

Looking to integrate the date, month, and year selection tags into the inline format

The Edit User Profile page includes a Birthday field, which is currently displayed vertically. I am looking to change the layout so that the Birthday field appears horizontally. Here is the code I am using: Within visitors/edit.html.erb, <%= simple_f ...

Ensuring form field accuracy through server-side validation using Ajax - Mastering the art of Ajax

I am in need of implementing Ajax to validate my form fields, currently I have a javascript validation set up. Is it possible to reuse my existing javascript code and integrate Ajax for form validation? HTML Form <form method="post" action="ajax/valid ...

Mismatched data types for function arguments

const x: Example = { toY: (y: Maple) => { return y.p; } }; interface Example { toY: (y: Pine) => void; } interface Pine { c: string; } interface Maple extends Pine { p: boolean; } Despite the warning for interface names ...

JavaScript tutorial: Locate a specific word in a file and display the subsequent word

Seeking assistance with a task: I need to open a locally stored server file, search for a specific word, and then print the next word after finding the specified one. I have managed to write code that successfully opens the file, but it currently prints e ...

Is there a method to redirect and display a JavaScript message efficiently?

Once the user has updated a record, I want to automatically redirect them to another page where they will be notified with a JavaScript message (alertify.notify()) confirming that the update was successful. I am unsure if it's possible to dynamically ...

Steps to include a title next to a progress bar:

Is there a way to achieve something like this? I attempted to use bootstrap but I ran into an issue where the title was slightly misaligned below the progress bar. Can someone offer assistance with this matter? Apologies if this has been asked before. H ...

Exploring the getJSON function within jQuery

{ "Emily":{ "Math":"87", "Science":"91", "Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d6f7e767c51767b727e737f764f747879">[email protected]</a>", "City":"Chicago" }, "Sa ...

Customize Vuetify Menu by adding a unique custom keypad component for editing text fields

I am currently developing an app using vuetify, and I am encountering some challenges with the v-menu feature. The issue arises when I click on a text input field, it triggers the opening of a v-menu. Within this menu, there is a custom component that I h ...

Exploring the Integration of jQuery AJAX in a Contact Form

I would like to incorporate AJAX functionality into a contact form. Here is the current code I have... $("#contact_form").validate({ meta: "validate", submitHandler: function (form) { $('#contact_form').hide(); ...

performing a GET request directly from a <script> element in the index.html file

I am currently developing an application that utilizes Angular.js on the client side and Node Express on the server side. On my server side, I am using a staticAsset module. Within my index.html file, I have a lengthy list of JavaScript files that need t ...

Using JavaScript to obtain the coordinates of a click event from a programmatically triggered click on an HTML element

Is there a way to programmatically simulate a click event on an HTML DOM element and still retrieve the screenX/screenY and clientX/clientY coordinates successfully? When manually clicking the element, the coordinates are visible in the console, but when t ...

directive ng-click not responding

drawer-card.html (template) <div class="drawer-card-wrapper"> <div class="drawer-card-icon" ngClick="dcCtrl.toggle()"> <i class="icon--{{ icon }}"/> </div> <div class="{{'drawer-card ' + (classesToAdd || '&apo ...

Upon rerender, React fails to refresh the style changes

I am encountering an issue with my React component where the visibility and position can be changed by the user. Currently, the visibility can be toggled by adding or removing a CSS class, while the position is adjusted through a function that updates the ...

"Setting the minimum length for multiple auto-complete suggestions in

How can I dynamically set the minLength of an input field based on whether a numeric value is coming from the "#lookup" field? Is there a way to achieve this using JavaScript and jQuery? <script type="text/javascript"> $(document).ready(function() ...

Performing addition operations on numbers entered through an HTML input field using PHP

I am looking to create a feature where the numbers entered in an input form are added together. I need to store these numbers in an array and have them display in a new line when a button is clicked. Here is the HTML code for the input field and button: ...