Error 504: The timeout issue occurred during an ajax call

When I make an ajax call to process a large amount of data and then reload the page upon success, I encounter a 504 Gateway Timeout error. The ajax call is initiated with the following parameters:

$.ajax({
    type:'POST',
    cache:false,
    async:false,
    url: 'URL',
    data: "",
    timeout:0,
    beforeSend:function(msgg){   
        $('#loading').show();
    },
    success: function(data){
        if(data == "success")
        {
            setTimeout(function(){
                $('#loading').hide();
                window.location.reload();
            },5000);
        }
    }
});

Despite my efforts, the ajax call never reaches the success stage and results in the 504 Gateway Timeout error. As a workaround, I am manually refreshing the page.

Answer №1

504 GATEWAY_TIMEOUT errors may occur when the URL of your API Gateway is unresponsive, often due to an internal Gateway error.

Follow these troubleshooting steps:

  • Utilize a proxy tool such as Postman to replicate the request and check the response
  • Verify that the path is accurate
  • If other requests are being made to the same gateway URL, test them manually or through your code to ensure the gateway functions properly
  • If feasible, restart the Gateway (particularly possible in Microservices architecture with Dockerisation)

Answer №2

To improve performance, it is recommended to make shorter calls to check status or retrieve data.

If the above recommendation is not feasible, consider the following alternative:

Note: This solution is not suitable for production environments or high traffic situations. It is advisable to perform this action on a dedicated server.

For users of Apache Web Server 2.4, the default TimeOut directive is set to 60 seconds.

For more information, refer to this resource.

The web server will maintain the connection open for only 60 seconds irrespective of the max_execution_time

While the php.ini setting max_execution_time controls PHP execution time, the Apache TimeOut directive determines the maximum connection duration.

For instance:

  • If the php max_execution_time is 120 sec, but the TimeOut is set to 30 sec, a 504 error may occur
  • If the php max_execution_time is 120 sec, but the TimeOut is extended to 300 sec, the script will run for a maximum of 120 seconds while the connection remains active for 300 seconds

In the absence of a specified response code from PHP, a successful operation returns a 200 status code, while an error results in a 500 status code.

Unexpected HTTP Response codes should prompt monitoring of the web server as well.

Answer №3

When faced with the issue of a browser not being able to handle long ajax calls, I decided to utilize ajax recall and process the data in smaller parts. This approach effectively resolved the problem.

Answer №4

Encountered a functional solution shared by #david-hoerster

According to his explanation, if your error event handler accepts the three parameters (XMLHttpRequest, textstatus, and message) and a timeout occurs, the status argument will be 'timeout'

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});​

Using jsFiddle, you have the ability to test ajax calls -- it will wait 2 seconds before responding. I set the timeout at 1 second, so it should trigger an error and return a textstatus of 'timeout' to the error handler.

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

Load nodes for jsTree based on the results of a query when requested by the user

I've been researching extensively, but I have yet to discover the correct solution. I am interested in learning how to dynamically generate a jsTree where the nodes are loaded from a database. The data will be retrieved by a function. My objective i ...

Having trouble with the full-screen feature not functioning properly?

I am currently in the process of creating a custom video player and I need to include a full-screen button. However, when I click on it, the video does not expand to fill up the entire screen. I am using javascript, css3, and html5 for this project. Any as ...

Upon mounting, componentDidMount method will likely return an undefined object when using axios

Currently, I am facing an issue where I am attempting to retrieve a JSON and incorporate it into my state. Interestingly, when I trigger my ajax request using axios within the componentDidMount lifecycle method, and then print out the updated state inside ...

Error: The 'price' property is undefined and cannot be read at path C:NODEJS-COMPLETE-GUIDEcontrollersshop.js on line 45, character 37

I have been attempting to add my products to the cart and calculate the totalPrice, but I keep encountering an error. Here is the error message:- enter image description here. Below is the code from my shop.js file:- exports.postCart = (req, res, next) =&g ...

What methods are available for implementing hover effects within attributes using a JavaScript object?

const customPanelStyle = { 'background-color': 'red', 'border': '1px solid green', ':hover'{ 'background': 'blue' } } class some extends React.Component{ rende ...

Tips on sending an array to material-ui dataSource props

Currently utilizing material-ui for a component. I am facing an issue with the autocomplete component in material-ui where I intend to display a list of icon names along with the icons. When only passing MenuItem to dataSource, it results in an empty input ...

Tips for identifying modifications in an input text field and activating the save button

Currently, I am developing a function that can detect any changes made in the text field and then activate the save button accordingly. This code is being executed in Visual Studio 2017, using HTML and JavaScript. (function () { var customer_addres ...

The values obtained from the previous parameter object of the React setState hook can vary and are not always

In my code, I am using a useEffect hook to update the state with setState. However, I'm encountering some unusual and inconsistent behavior with the previous parameter: useEffect(() => { setCurrentPicturesObject((existing) => { ...

What is the importance of setting up an HTTP server?

Can anyone explain why, in nodeJs programming with javascript, it is necessary to establish a server using the http module, even though one could simply utilize the fs module for reading, writing, and updating data stored in a json file? ...

Tips for uploading information and posting it on a different page with mongoDB and Node.js

I am looking to implement a feature on a website where data is submitted to MongoDB from one page, and then retrieved and displayed on another page. The technologies I am working with include node.js, express, Mongoose, and MongoDB. Currently, the data is ...

A guide to retrieving information from PHP using jQuery AJAX

I am a beginner in the realm of ajax, but my enthusiasm to learn is unwavering. I recently established a form using Formidable Pro that submits data via ajax. Within the submit button, I have incorporated an onclick function: <div class="frm_submit"> ...

Deciphering the evolution of APIs and managing internal API systems

I'm currently exploring the world of APIs and I have a few questions that are puzzling me. Question1: I understand that APIs facilitate communication between different applications. But why would a company need an API for internal use? For example, i ...

The HTML object is experiencing difficulties with the Ajax page loader feature not functioning as

I attempted to use the code below in order to show an Ajax loader image while the page loads into an HTML object. Unfortunately, it didn't work as expected and I'm having trouble figuring out why. Everything seems to be functioning correctly exce ...

Cart cannot function as a constructor

I'm currently learning express.js and trying to implement a shopping cart/session functionality into my project. Below is the code I have written so far, with a question at the end. Here is my cart.js: // Ensure that the file is required correctly b ...

Determine whether AngularJS directive method binding automatically defaults to angular.noop

In my directive, I am passing a function to a plugin which will use it with a specified value. Let's simplify things by ignoring data changes: angular.module('some.directives', []) .directive('myDirective', [, function () { ...

Is it possible to await the response of a request in Socket.io with socket.on('answerToRequest')?

Can the following scenario work out? async function checkSocketStatus(){ socket.emit('checkOtherSocketStatus', otherSocketId); await socket.on('responseCheckSocketStatus', (status)=>{ console.log('status'); } ...

Showing HTML element when the model count is zero - ASP.NET MVC View

My view has a dynamic element that switches between two options depending on the Model.Count property. Check out the code below: @if (Model.Count() == 0) { <div class="well well-lg"><h3>Everyone is present! No absences today :)</h3>& ...

What sets apart the use of `function(){}.bind(this)` and `angular.bind(this, function() {})`

Can you highlight the difference between these two code snippets? function Ctrl($scope) { $scope.$watch(function() { return this.variable; }.bind(this), /*...*/); } and function Ctrl($scope) { $scope.$watch(angular.bind(this, functio ...

ReactJS encounters errors even when the backend is returning a 200 OK status code

My ReactJS frontend receives an error when sending a GET request, even though the django backend terminal shows [10/Mar/2018 23:31:08] "GET /post/ HTTP/1.1" 200 930. I am using redux sagas in my project. In src/index.js: (index.js code snippet here) In ...

Struggling to display filtered content in React using State

As a newcomer to React, I am working on a todo list that shows both current and completed tasks using LocalStorage. Each task has a boolean property called "active" which is toggled when a user clicks on the task checkbox. I have a filter in place to separ ...