Redirect POST Request

JavaScript Redirect POST Request Without Data Limit

Rather than AJAX staying in the same HTML, sometimes, developers have to redirect to different URL using POST requests. We provide tricky JavaScript codes to redirect a POST request with no parameters limit. Comparison with GET request method are given in the example, too.

All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.

Estimated reading time: 5 minutes

EXPLORE THIS ARTICLE
TABLE OF CONTENTS

BONUS
Source Code Download

We have released it under the MIT license, so feel free to use it in your own project or your school homework.

Download Guideline

  • Prepare HTTP server such as XAMPP or WAMP in your windows environment.
  • Download and unzip into a folder that http server can access.

SECTION 1
Redirect POST Request

Originally, HTTP designs its redirection using GET requests, while developers may have some concerns and would like to redirect to other URLs by POST requests. Let’s discuss about the topic.

HTTP GET & POST

Traditionally, using JavaScript, users redirect a GET request just by clicking, but would have to fill in a form to redirect a POST request. Indeed, GET requests are safe beyond seeing some parameters in browsers users might not want to see.

The reason why people would like to redirect a POST request in JavaScript could be that POST requests can make parameters unseen in browsers.

GET Request by A Href

usually redirect GET requests. Therefore, people think that GET requests are simple, and idempotent behaviors.

POST Request by Form

needs more complex input and submit actions than to redirect a POST request in HTML. To reduce coding efforts, we will introduce a general way in JavaScript allowing to pass unlimited POST parameters in a request.

SECTION 2
The Example

The section demonstrates distinct methods to redirect URLs. Moreover, we create a JavaScript function available to redirect a POST request with unlimited POST data parameters.

Читайте также:  Рынок java в россии

Client-Site Script

We prepare both GET request and POST request in the example. As mentioned in the previous section, implements GET request, while redirect POST request in JavaScript.

Redirect POST Request in JavaScript

The codes is a GET request. It is easy to increase more GET parameters in one transaction. For POST request, there should be some tips inserting more POST parameters into Form object.

        Click to Redirect a GET Request

For example, we define a JavaScript object containing 5 data elements. In a function, the content of object forms a series of HTML element with name and value, i.e. key and value from the view of server sites. Eventually, function postRedirect() can play the role and redirect POST request in JavaScript with unlimited POST parameters.

Server-Site Script

Due to similarity, we ignore the server script for GET requests, and just focus on that for POST requests as below.

        
$value) < echo "

$key => $value

"; > ?>

The redirected page lists POST data parameters received.

Post Parameters in Server Sites

In addition, the example layout is decorated by the following CSS file.

FINAL
Conclusion

Though it is a trick to redirect URLs, some people need such a function to improve coding efficiency. Without such an approach of HTML code generation in JavaScript, it is hard to redirect a POST request without POST data limit.

Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!

Learning Tips

Let us suggest a excellent way to learn HTML scripts here. Using Google Chrome F12 Inspect or Inspect Element will help you study the codes.

In Google Chrome, there are two ways to inspect a web page using the browser built-in Chrome DevTools:

  • Right-click an element on the page or in a blank area, then select Inspect.
  • Go to the Chrome menu, then select More Tools > Developer Tools.

Suggested Reading

TRY IT
Quick Experience

That is all for this project, and here is the link that let you experience the program. Please kindly leave your comments for our enhancement.

Try It Yourself

Click here to execute the source code, thus before studying the downloaded codes, you can check whether it is worthy.

Источник

Редирект после POST запроса

Каждый веб-разработчик знает, что после POST сабмита формы желательно сделать редирект, чтобы предотвратить повторную отправку данных, когда пользователь захочет обновить страницу. В основном это критически необходимая операция, так как данные формы могут сохраняться в базе данных или участвовать в платёжной транзакции. И тогда данные не только продублируются, но и спишутся лишние деньги.

Читайте также:  Python distutils site packages

Но речь не о деньгах, а о правильном редиректе…

Практически все веб-приложения при редиректе POST запроса возвращают статус 302 Found. Например, в php редирект делают так: header(‘Location: /new/location’);. Без дополнительных параметров или если отдельно не указан другой статус, функция вернёт именно 302 Found.

Теперь обратимся в официальным документам. В RFC 2616 сказано следующее:
If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Если статус 302 получен в ответ на запрос отличный от GET или HEAD, юзер-агент НЕ ДОЛЖЕН автоматически редиректить запрос до тех пор, пока он не будет подтверждён пользователем, так как это может нарушить условия запроса.

Там же в заметках написано, что несмотря на это, многие юзер-агенты пренебрегают этим правилом и интерпретируют 302 статус как 303. А пошло это ещё со времён HTTP/1.0, в котором 303 статуса ещё не было.

Т.е. для редиректа POST запроса нужно использовать статус 303 See Other, который специально для этого и предназначен. В php редирект будет выглядеть, например, так: header(‘Location: /new/location’, true, 303);

В RFC в заметке к статусу 303 написано:
Many pre-HTTP/1.1 user agents do not understand the 303 status. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303

Многие пре-HTTP/1.1 юзер-агенты не понимают 303 статус. Если совместимость с такими клиентами важна, то вместо него можно использовать 302 статус, так как большинство таких агентов реагируют на 302 статус также как на 303.

И получается два варианта:
1. По прежнему использовать 302;
a. есть вероятность нарваться на юзер-агента, который чтит спецификацию и выдаст предупрежление.
б. так как такое поведение не стандартно, можно нарваться на вообще непредсказуемый результат.

2. Использовать 303, тогда старые клиенты не поймут, что от них хотят.

Во втором случае, можно анализировать версию протокола, запрошенную клиентом, и выдавать 302 для старых клиентов. В теле ответа писать ссылку на новый УРЛ. Тогда пользователь старого агента, сможет хотя бы кликнуть на ссылку.

Источник

Html post and redirect

  • The basics of TOGAF certification and some ways to prepare TOGAF offers architects a chance to learn the principles behind implementing an enterprise-grade software architecture, including.
  • Haskell vs. PureScript: The difference is complexity Haskell and PureScript each provide their own unique development advantages, so how should developers choose between these two .
  • A quick intro to the MACH architecture strategy While not particularly prescriptive, alignment with a MACH architecture strategy can help software teams ensure application .
  • Postman API platform will use Akita to tame rogue endpoints Akita’s discovery and observability will feed undocumented APIs into Postman’s design and testing framework to bring them into .
  • How to make use of specification-based test techniques Specification-based techniques can play a role in efficient test coverage. Choosing the right techniques can ensure thorough .
  • GitHub Copilot Chat aims to replace Googling for devs GitHub’s public beta of Copilot Chat rolls out GPT-4 integration that embeds a chat assistant into Visual Studio, but concerns .
  • 4 popular machine learning certificates to get in 2023 AWS, Google, IBM and Microsoft offer machine learning certifications that can further your career. Learn what to expect from each.
  • Navigate multi-cloud billing challenges Keeping track of cloud bills from multiple clouds or accounts can be complex. Learn how to identify multi-cloud billing .
  • 5 Google Cloud cost optimization best practices Cost is always a top priority for enterprises. For those considering Google Cloud, or current users, discover these optimization .
  • Coveware: Rate of victims paying ransom continues to plummet Incident response firm Coveware said 34% of ransomware victims paid the ransom in Q2 2023, a sharp decline from last quarter and .
  • Mandiant: JumpCloud breach led to supply chain attack Mandiant researchers attribute the supply chain attack to a North Korean threat actor that abused JumpCloud’s commands framework .
  • BrightTALK @ Black Hat USA 2022 BrightTALK’s virtual experience at Black Hat 2022 included live-streamed conversations with experts and researchers about the .
  • AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
  • Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
  • Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .
Читайте также:  Java text field get text

Источник

Оцените статью