Home > Blockchain >  Get ajax call progress status in front end
Get ajax call progress status in front end

Time:12-20

I have a web page which allows users to upload and process specific files. After an user uploads some files, after clicking the 'Process' button an ajax call is being sent to a backend service. In the beforeSend function there is an overlay applied to the screen and a spinner is displayed. When the success function is triggered, then the overlay is removed and a toast notification is being shown like 'Files were processed!' My goal is to somehow show a progress status for each file based on specific checkpoints in the backend service. Let's say that the backend service when called does following tasks: parse file, map to specific format, send data to database A.... and in the end it sends back http status 200 and a JSON like

{
   "status":"Success",
   "message": "File X was processed"
}

Now what I want is that instead of just getting an overlay and disabling the whole page until the success event is triggered, to have a progress bar which is updated for each file based on the exact step where the backend has reached.

For instance, for file A, I would like to see below transitions: 5 % Parsing file, 10 % Mapping file...90% sending data to database, 100% processed.

Is this somehow achievable?

CodePudding user response:

An HTTP request consists of a request and a response. There's no direct way to get status updates beyond the onprogress event which would let you see how much data has been transferred. This is useful for determining how much of the data has been sent to the server, but not so much for how far the server has got with working with that data.

You could store progress in a database and poll a webservice to read the most recent status.

You could also have the server push updates to the client using Websockets for bi-directional communication.

A rough outline for such a system might look like:

  1. Open a Websocket
  2. Send files with Ajax
  3. Get server generated ID back in HTTP response
  4. Pay attention to messages coming over the Websocket that mention that ID

You could also look at doing the whole thing over Websockets (i.e. upload the files that way too). A quick Google search turns up this library for uploading files to a Websocket service hosted on Node.js. 3. Listen for messages from the server

CodePudding user response:

Your Ajax call should be asynchronous. So it returns immediately after it sent the request to the backend. The backend is now proceeding the request and stores the actual status somewhere (can be a file or a database table or something else) On the front end you can now start a set interval function which is starting another Ajax request every x seconds. This request is calling a backend script which just returns the status which it is reading from this file or database. That’s all.

  • Related