I am not a JS guy (can write some basic stuff), I am working on integrating our Payment API with the front end, as part of the process, we want to trigger a timeout in case my back-end Payment API is not responding within a given timeframe. Here is the JS code which interacting with the Payment API.
performAuthorizePaymentRequest: function (payment) {
return new Promise(function (resolve, reject) {
$.ajax({
type: 'POST',
url: encodedContextPath + '/checkout/authorise_order',
data: JSON.stringify(payment),
dataType: 'json',
contentType: 'application/json',
success: resolve,
error: reject,
always: function () {
pageSpinner.end()
},
timeout: 30000 /* call this.session.completePayment() within 30 seconds or the payment is cancelled */
});
});
}
This seems to be working fine, however I have seen the following issue.
- In case m backed API throws any error, the code is still waiting for the timeout.
- Even for success cases, the js is waiting for timeout before showing success message.
Is there a way to handle this? Let me know in case I am doing something wrong here.
Note: This code will only execute of Safari, for other browser this is not available
7
Answers
I would avoid a timeout in the ajax call, but would go to a with a
set_time_limit(30)
in the php (if your /checkout/authorise_order is a php…)if the answer arrive before, all fine (won’t wait untill 30sec) it’s a time limit…
For javascript part I use my own :
in this function
pcache
if crucial to avoid caching because the purpose of api calls is to have a different answer each time…in the
params
you can add extra stuff too and it will pass it to phpIf you use php curl or shell curl, there is also max time mechanisms
setInterval()
method this method will repeat your code automatically for many times you can create a condition if event happend stop thissetInterval()
functionExample
You can abort the timeout like this maybe ? the example is at error, but you can do the same at success
});
I would recommend sticking to fetch instead of ajax because it timeouts after 300s by default and does fail if the server returns an error.
You can also abort the request before the default timeout using an abort controller https://developer.mozilla.org/en-US/docs/Web/API/AbortController.
The same code in fetch would be:
You can use the
abort
method of theXMLHttpRequest
object and then set a timeout to abort the request after 30 seconds. Like so:See XMLHttpRequest.abort reference
Another approach is to have the
success
function cease to work after 30 seconds by setting a status flag to ‘out of time’. See comments in the code below:You can using promise.race().
Example:
Use:
ref: anonystick.com