0

I have this code:

$.ajax({
    type: "POST",
    url: "/pro_signup",
    data: { data: data, key: key },
    dataType: "json",
    success: function (response) {
      document.getElementById("purchase").innerHTML =
        '<button class="btn btn-primary button-connected">Verifying...</button><p class="grey-text">Waiting for verification...</p>';
      window.location.href = "/pro_account";
    },
    error: function (exception) {
      document.getElementById("purchase").innerHTML =
        '<button class="btn btn-primary button-error">Failed</button><p class="grey-text">Verification has failed.</p>';
    },
  });

I have a route in my flask backend /pro_account that must only accept POST requests, so in success in the code above I cannot use window.location.href = "/pro_account";

How do I change this part (or the entire code) to make a post request on success to redirect to the /pro_account URL?

Olney1
  • 572
  • 5
  • 15
  • 1
    you can use `form` with `action="/pro_account"` and method="post" . and submit it when ajax response success – Xupitan Jun 06 '22 at 07:05
  • Ah ok, I must not have looked at this because I'm not using a form in the HTML or on the page? I'm just using a button. The button action is already responsible for initiating another script. – Olney1 Jun 06 '22 at 08:00
  • Do you have an example please that you can show me? – Olney1 Jun 06 '22 at 09:00
  • 1
    you can create form by js and submit it : https://stackoverflow.com/questions/6964927/how-to-create-a-form-dynamically-via-javascript – Xupitan Jun 06 '22 at 09:39
  • 1
    or by jquery : https://stackoverflow.com/questions/8003089/dynamically-create-and-submit-form – Xupitan Jun 06 '22 at 09:40

1 Answers1

0

Thanks to @Xupitan for pointing me in the right direction. I actually used this answer in the end: https://stackoverflow.com/a/9252533/16673529

Resulting code:

$.ajax({
        type: "POST",
        url: "/pro_signup",
        data: { data: data, key: key },
        dataType: "json",
        success: function (response) {
          //console.log(response);
          $("#var1").val(response);
          $("#form").submit();
        },
        error: function (exception) {
          document.getElementById("purchase").innerHTML =
            '<button class="btn btn-primary button-error">Failed</button><p class="grey-text">Verification has failed.</p>';
          //console.log(response);

with this HTML:

<form style="display: none" action="/pro_account" method="POST" id="form">
      <input type="hidden" id="var1" name="var1" value="" />
    </form>
Olney1
  • 572
  • 5
  • 15