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

What is the technique for causing this element to move in reverse?

How can I utilize JS to halt the interval and direct the alien to move backwards once it reaches 700px? I am aware that CSS can achieve this, but I prefer a strictly JS approach. I am struggling with stopping the interval as it hits the left position of 70 ...

Implement the window.open functionality within a directive for optimal performance

I am attempting to activate the function $window.open(url, windowName, attributes); in my Angular application by using an ng-click event. I have created a directive and enclosed the window.open method within a trigger function that is connected to a butto ...

Tips for keeping components mounted despite changes in the path

How can I maintain state in React routes to prevent unmounting when switching between them? In my application, it's crucial to keep the state intact during route changes. When changing routes, the respective components mount and unmount. How can this ...

How can you identify when a Vuetify radio button is re-selected?

Currently, I am developing a wizard that involves triggering navigation when a radio button is selected. Users should also be able to go back and change their previous choices. However, one issue I have encountered is the difficulty in detecting a re-selec ...

The Hyperledger Sawtooth JavaScript SDK has encountered invalid submitted batches

I am currently working on integrating a hyperledger sawtooth transaction using the javascript SDK. I am following the tutorial provided here: . /* *Create the transaction header */ const createTransactionHeader = function createTransactionHeader(payloadBy ...

Adhering button for sliding side panel

Check out my JSFiddle HERE to see what I have done. I would really appreciate it if someone could help me figure out how to make the show button float with the sidr panel :) <style type="text/css"> #panel { position: fixed; top: 50%; r ...

AngularJS - Choose and establish initial values for Editing or Creating New Items

My first project involving AngularJS has left me a bit stuck when it comes to using the select list. I need to either set the default value to the first option for a new entry, or if it's an edit, select the appropriate value. In my form, there are t ...

What is the best approach to updating multiple rows instead of just the first row using the update button located on both sides using PHP and AJAX?

Starting fresh, so I might sound like a beginner with this question. How can I make use of the update button to update specific rows instead of just the top row? Every time I try to update, it only works for the top row. Here's the code snippet from ...

Issue detected: data exceeds limits (length=3, offset=32, code=BUFFER_OVERRUN, version=abi/5.0.7) within next-js and ethereum

While working on my Ethereum and Next.js project, I encountered an error during the initialization of the project: Error: data out-of-bounds (length=3, offset=32, code=BUFFER_OVERRUN, version=abi/5.0.7) at Logger.makeError (/home/Documents/projects/eth ...

Ways to effectively utilize jQuery objects as arguments in the delegate function

When working with delegate and multiple selectors, you can use the following syntax: $(contextElement).delegate('selector1, selector2' , 'eventName', function(){ //blabla }); In projects where managing DOM elements is important, stori ...

Halt period indicated in the document specifying the designated timeframe

If I have two files named index.php and fetch.php The contents of index.php are as follows: <script> $(document).ready(function(){ setInterval(function(){ $('#fetch').load('fetch.php') }, 1000); }); </sc ...

Why doesn't the div click event trigger when the mouse hovers over an iframe?

My dilemma involves a div element with a click event. When the div is positioned over an iframe area (closer to the user than the iframe), the click event fails to trigger. However, if the div is located elsewhere and not above the iframe, the click event ...

Retrieving a single object in NEXT.JS and MongoDB can be achieved by returning just a single object

Is there a way to retrieve a single object instead of an array from the API? I am specifically looking for just a single "Event" while using MongoDB and Next.js. Currently, I always receive: [{}] But I would like to receive: {} const fetchWithId = (url ...

When only showing the title to the client, it results in an undefined value

I have created a schema in mongoosejs that looks like this: var uploadSchema = mongoose.Schema({ title : String, happy : String, }); I am trying to show the data from my database on the client side (using ejs for templating) ...

Guide to Spidermonkey Bytecode Documentation

I've been searching for a comprehensive guide to spidermonkey's bytecodes for some time now, or at least something that gives me an overview of their purpose. Does anyone know of a good resource for this? Thank you! ...

Unable to replicate the functionality of the tab key using jQuery for the enter key

How can I focus on the first input ('Qtd on the table') after pressing enter on the 'Buscar' input? I've tried various solutions like $(this).nextAll('input').first().focus(); $(this).next('input:text').focus ...

Node.js poses a challenge when it comes to decoding incoming request data

I am attempting to create a sample login page using the combination of node, express, and angularjs. Displayed below is my login view: <div class="login-page"> <div class="login-page-content"> <div style="margin-top:30px;padding:10px;w ...

Utilizing Stored Variables and Random Numbers in Selenium IDE

Can you explain how Selenium IDE handles stored variables (stored text) and random numbers? I've been trying to combine the two without much success. For example: <td>type<td> <td>css=input.some-text</td> <td>javascript ...

Is it possible to extract my current location from one website and then access another website based on that location?

I am currently experimenting with an HTML5 script that loads a globe requiring users to click on it to determine the location. Once a location is clicked, another site opens displaying a map of the chosen location. Here is an example of the site with the i ...

LiveValidation plugin causing issue with removing dynamically inserted elements

My form validation is powered by the Live Validation plugin. After submission, the plugin automatically inserts a line of code like this one: <span class=" LV_validation_message LV_valid">Ok</span> However, I encountered an issue when trying ...