How to prevent duplicate submission in jquery project

How to prevent duplicate submission in jquery project

In new projects, axios can prevent duplicate submissions, but old projects (such as jQuery) do not have axios. But importing Ajax-hook
It can be achieved

Ajax-hook source code address: https://github.com/wendux/Ajax-hook

Import

<script src="https://unpkg.com/[email protected]/dist/ajaxhook.min.js"></script>

The ah object appears after importing ajaxhook.min.js, use:

ah.proxy({
    //Enter onRequest before request is initiated: (config, handler) => {
        console.log(config.url)
        handler.next(config);
    },
    //Enter when a request error occurs, such as timeout; note that this does not include http status code errors, such as 404, which will still consider the request successful onError: (err, handler) => {
        console.log(err.type)
        handler.next(err)
    },
    //After the request is successful, enter onResponse: (response, handler) => {
        console.log(response.response)
        handler.next(response)
    }
})

Among them, config.method is the ajax request method (GET/POST), and config.url is the requested path. The err object in onError and the response in onResponse can obtain the ajax request method through err.config.method/response.config.method.

I encapsulated it a little bit and implemented a js file to prevent duplicate submission. It has been tested and is effective. Friends can test it later. All experts are welcome to discuss and point out deficiencies.

```javascript
function laodJS(url, callback) {
  var script = document.createElement('script');
  fn = callback || function() {};
  script.type = 'text/javascript';
  script.defer = true;
  //IE
  if (script.readyState) {
    script.onreadystatechange = function() {
      if (script.readyState == 'loaded' || script.readyState == 'complete') {
        script.onreadystatechange = null;
        fn();
      }
    }
  } else {
    // Other browsers script.onload = function() {
      fn();
    }
  }
  script.src = url;
  document.getElementsByTagName('body')[0].appendChild(script);
}
laodJS('https://unpkg.com/[email protected]/dist/ajaxhook.min.js', function() {
  let ajaxArr = []
  ah.proxy({
    //Enter onRequest before request is initiated: (config, handler) => {
      var id = config.method + config.url
      if (ajaxArr.indexOf(id) === -1) {
        // Set a unique ID for each request and push it to ajaxArr. When the request is completed, remove the item ajaxArr.push(id)
        handler.next(config);
      } else {
        return handler.reject()
      }
    },
    //Enter when a request error occurs, such as timeout; note that this does not include http status code errors, such as 404, which will still consider the request successful onError: (err, handler) => {
      var id = err.config.method + err.config.url
      if (ajaxArr.indexOf(id) !== -1) {
        ajaxArr.splice(ajaxArr.indexOf(id), 1)
      }
      handler.next(err)
    },
    //After the request is successful, enter onResponse: (response, handler) => {
      var id = response.config.method + response.config.url
      if (ajaxArr.indexOf(id) !== -1) {
        ajaxArr.splice(ajaxArr.indexOf(id), 1)
      }
      handler.next(response)
    }
  })
})

Just import this file globally. I named this file preventRepeatSubmission.js.

My HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <h1>This is index Page</h1>
  <ul>
    <li><a href="/">/</a></li>
    <li><a href="/index">index page</a></li>
    <li><a href="/404">404 page</a></li>
    <li><a href="/info">info page</a></li>
    <li><a href="/nofound">nofound</a></li>
  </ul>
  <button id="sendMsg">Request Interceptor</button>
  <script src="./jquery.min.js"></script>
  <!-- <script src="https://unpkg.com/[email protected]/dist/ajaxhook.min.js"></script> -->
  <script src="./preventRepeatSubmission.js"></script>
  <script>
    document.getElementById("sendMsg").addEventListener("click", function() {
      $.ajax({
        url: 'http://localhost:3000/home',
        type: 'GET',
        success: function(data) {
          console.log('success', data)
        }
      })
    })
  </script>
</body>
</html>

My server is built using koa2, the code is as follows:

const Koa = require('koa');
const Router = require('koa-router');

const app = new Koa();
const router = new Router();

router
  .get('/', (ctx, next) => {
    ctx.body = '<h1>hello jspang</h1>';
  })
  .get('/home', async (ctx, next) => {
    // ctx.body = '<h1>This is home Page</h1>'
    async function delay(time) {
      return new Promise(function(resolve, reject) {
        setTimeout(function(){
          resolve();
        }, time);
      });
    };
    await delay(5000);
    const url = ctx.url;
  
    // Get the get request parameters in request const request = ctx.request;
    const request_query = request.query;
    const request_querystring = request.querystring;

    // Get the parameters of the get request in ctx const ctx_query = ctx.query;
    const ctx_querystring = ctx.querystring;
    ctx.body = {url, request_query, request_querystring, ctx_query, ctx_querystring};
    ctx.response.body = {status:200, msg:'Parameters have been successfully obtained'};
  })

app
  .use(router.routes()) // Load routes into app.use(router.allowedMethods()) // Load middlewareapp.listen(3000, () => {
  console.log('[Demo] is running at port 3000');
});

Browser test results:

Pressing the button in the picture will initiate an ajax request. My server delayed the response by 5s. During the 5s delay, I clicked the button 20 times, and the same 20 ajax requests were successfully intercepted, which worked well.

Summarize

This is the end of this article about how to prevent duplicate submission in jquery projects. For more relevant jquery anti-duplicate submission content, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Two ways to prevent duplicate submissions with jQuery's $.ajax (recommended)
  • jQuery prevents form from being submitted repeatedly
  • How to prevent repeated submission when submitting a form in jQuery
  • Jquery Validation plugin prevents duplicate form submissions
  • A brief analysis of the reasons why jquery repeatedly submits requests
  • How to prevent Ajax from submitting repeatedly using jQuery

<<:  CSS margin overlap and how to prevent it

>>:  Solution to interface deformation when setting frameset height

Recommend

Docker image loading principle

Table of contents Docker images What is a mirror?...

VPS builds offline download server (post-network disk era)

motivation Due to learning needs, I purchased a v...

Uniapp's experience in developing small programs

1. Create a new UI project First of all, our UI i...

CSS Viewport Units for Fast Layout

CSS Viewport units have been around for the past ...

Example code for implementing anti-shake in Vue

Anti-shake: Prevent repeated clicks from triggeri...

js realizes 3D sound effects through audioContext

This article shares the specific code of js to ac...

Summary of commonly used SQL statements for creating MySQL tables

Recently, I have been working on a project and ne...

About the configuration problem of MyBatis connecting to MySql8.0 version

When learning mybatis, I encountered an error, th...

MySQL slow query: Enable slow query

1. What is the use of slow query? It can record a...

How to restore docker container data

The project test environment database data is los...

Tutorial on building an FTP server in Ubuntu 16.04

Ubuntu 16.04 builds FTP server Install ftp Instal...

How to run the react project on WeChat official account

Table of contents 1. Use the a tag to preview or ...

Detailed explanation of the murder caused by a / slash in Nginx proxy_pass

background An nginx server module needs to proxy ...