A straightforward interval-based Ajax request

I've recently delved into the world of Ajax and jQuery. Just yesterday, I embarked on creating a simple ajax request for a form that sends a select list value to a PHP script and retrieves data from a database.

Things are going smoothly so far! However, there's a slight hiccup - when I click on the send button, it initiates the request after a 1-second delay. I suspect this issue is related to my interval setup. Each time I press the send button, the request kicks off immediately but also repeats every second to allow for auto-refreshing of new income entries.

Ideally, I would like this interval cycle to happen every second, but the first time I click the button, I want it to load instantly instead of waiting for 1 second.

You can find the code snippet here: http://jsbin.com/qitojawuva/1/edit

$(document).ready(function () {

    var interval = 0;
    $("#form1").submit(function () {

        if (interval === 0) {
            interval = setInterval(function () {


                var url = "tbladen.php";
                var data = $("#form1").serialize();

                $.ajax({
                    type: "POST",
                    url: url,
                    data: data,
                    success: function (data) {
                        $("#tbladen").html(data);
                    }
                });
            }, 1000);
        }
        return false;
    });


});

Thank you!

Answer №1

Here’s a snippet of code that may suit your needs:

$(document).ready(function () {

    var isFirstTime = true;

    function submitForm() {
        var url = "tbladen.php";
        var formData = $("#form1").serialize();

        $.ajax({
            type: "POST",
            url: url,
            data: formData,
            success: function (data) {
                $("#tbladen").html(data);
            }
        });

    }

    $("#form1").submit(function () {

        if (isFirstTime) {
            submitForm();
            isFirstTime = false;
        } else {
            setTimeout(function () {
                submitForm();
            }, 1000);
        }
        return false;
    });

});

Answer №2

It is recommended to utilize the setTimeout function instead of setInterval when your callback function needs a specific duration to finish its operation, as setInterval will continue running regardless of whether the callback has completed or not.

$(function () {

    $("#form1").submit(postData);

    function postData() {
        var url = "tbladen.php",
            data = $("#form1").serialize();        
        $.ajax({
            type: "POST",
            url: url,
            data: data,
            success: function (data) {
                $("#tbladen").html(data);
                setTimeout(postData, 1000);
            }
        });
        return false;
    }
});

Check out a related demo here

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

How can jQuery each() be combined with casperjs?

I'm struggling to echo the ids of elements that match my selector because I'm confused about two different uses of 'this'. When I want to echo something in CasperJS, I use this.echo(). However, when I'm using .each(), 'this&a ...

Using Vue to fetch JSON data with Axios

When trying to retrieve user data from a MongoDB in JSON format using axios.get within a Vue.js application, my aim is to visualize this data by iterating through all user objects in the users array. The issue I'm facing is that each character is trea ...

What is the method for identifying the name of a CSS Variable currently in use?

Consider this code snippet: /* css */ :root { --text-color: #666666; } input { color: var(--text-color); } In Javascript, how can I determine the name of the CSS custom property (variable) being utilized? // javascript console.log(document.querySel ...

What is the process for setting up both an open and closed status for my accordion?

After browsing through multiple threads on accordions, none seem to match my current structure which I believed was effective. In an attempt to learn and build elements from scratch, I created the following accordion with some help from Google and experi ...

Issue with accessing form in Angular 6 Reactive forms for custom validator functionality

I am facing an issue with creating a password validation for reactive forms in Angular. Every time I try to verify the password, I get a “Cannot read property 'get' of undefined” error in the console. I have tried different methods to access ...

Error: An unexpected symbol '<' was encountered after the build process in Vue.js

I just finished deploying a MEVN stack application to heroku. While everything is functioning properly locally, I am encountering a blank page and the following errors in the console post-deployment: Uncaught SyntaxError: Unexpected token '<' ...

I'm interested in developing a React function that generates recipe components based on a set of instructions provided in an array, along with a separate parameter specifying the recipe name

I am currently immersed in the book "Learning React" written by O'Reilly. The book mentions a method of creating components by using a function known as the "component creating function". It advises supplying the necessary parameters as the second par ...

The console is being flooded with API logging messages multiple times

My goal is to develop a search page for Pathfinder. I have crafted the following code in an attempt to retrieve data from the API. During the process of testing the fetch requests, I have noticed that when I console.log the fetched data, it appears multipl ...

Exploring ways to create simulated content overflow using react-testing-library

I have integrated material-table with material ui to develop a spreadsheet application. One of the features I have added is setting a maximum width of 50px for cells. If the content in a cell exceeds this width, it will display an ellipsis at the end of ...

I must first log a variable using console.log, then execute a function on the same line, followed by logging the variable again

Essentially, I have a variable called c1 that is assigned a random hexadecimal value. After printing this to the console, I want to print another hex value without creating a new variable (because I'm feeling lazy). Instead, I intend to achieve this t ...

Unable to locate module during deployment to Vercel platform

I have developed a website using NextJS. It functions perfectly when I run it through npm run dev, but when I try to build and deploy it on Vercel, I encounter an error stating that it cannot find the module. However, the module is found without any issues ...

Developing an Angular Chart with AJAX

Utilizing the power of angular-chart.js, I have successfully generated a chart with the provided code snippet. However, my goal is to dynamically generate a chart using AJAX calls. Unfortunately, when I attempt to load the chart through AJAX, it fails to r ...

Can Vue.js support two-way data-binding without the use of an input element?

Here is the code snippet that I'm working with: <div id="app"> {{ message }} </div> JavaScript: myObject = {message:"hello"} new Vue({ el: '#app', data: myObject }) When I update myObject.message, the content within th ...

Tips for setting the textfield value in JSP using Javascript

I am in need of a way to create a random number that will be displayed in the textfield once the user clicks on the "Generate" button. Can someone guide me on how to assign the value of the "output variable" to the "randomNum" textfield? Sample HTML code: ...

Develop an XML document with the use of either Javascript or PHP

I have an XML file that contains information about bracelets with photo details. <bracelets> <photo filename="b1.jpg" thumbnail="a1.jpg" description="aa" /> <photo filename="b2.jpg" thumbnail="a2.jpg" description="aa" /> & ...

Executing functionality based on changes in Angular bindings

I am working on securing user passwords in my HTML form. Currently, the password field is stored in localstorage like this: In JS: $scope.localStorage = localStorage; And then in HTML: <input id="pass" type="password" ng-model="localStorage.pass" re ...

Retrieve any webpage using AJAX

Hey there! I'm a beginner in AJAX and have a question that may seem basic to some. I understand that you can set up a page to respond to an AJAX call, but is it possible to request any page with AJAX? In other words, can all the functionalities of a ...

Directing users to a specific section on another webpage can be accomplished using HTML, JavaScript, or

<nav> <div class='container-fluid'> <h1 class='logo'>Logo</h1> <ul class='list-unstyled naving'> <li><a href='index.html'>Home</a></li> ...

JavaScript code to use Angular expressions in an HTML document

I am facing an issue with using Angular expressions inside JavaScript within an ng-repeat loop on my HTML page (note that the app and controller have been declared elsewhere): <div ng-repeat="eleRubrique in scopeComplet"> <script type="text ...

What is the best approach for manipulating live data in localStorage using ReactJS?

I am working on creating a page that dynamically renders data from localStorage in real-time. My goal is to have the UI update instantly when I delete data from localStorage. Currently, my code does not reflect changes in real-time; I have to manually rel ...