简体   繁体   中英

How can I redirect a user back from a page with no html/view?

I am doing a challenge, which uses Sinatra and Javascript and a JSON file as the database (of sorts) and have hit a roadblock that has been driving me nuts for two days. The issue is that I want to be able to be able to keep the user on the same page as the form /homepage (or redirect them back automatically) upon a successful submission and notify them of the successful submission from there. What actually happens is that once I submit the form, the user is redirected to the (POST) '/' route (and stays there) - however there is no view associated with that endpoint. What is being displayed is a server-side message.

Here is the config.ru:

##QUERY THE USERS LIST
get "/" do
  protected!
  File.open("./test-users.json").read
end

##ADD A NEW USER
post "/" do
  protected!
  param :name, String, required: true
  param :email, String, required: true, format: /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/

  contents = File.open("./test-users.json").read
  parsed_contents = JSON.parse(contents)
  File.delete("./test-users.json")
  parsed_contents["guests"] << {"email" => params["email"], "name" => params["name"]}
  File.open("./test-users.json", "w+") do |f|
    f.puts JSON.pretty_generate(parsed_contents)
  end

  "#{params['name']} now signed up with #{params['email']}"
end

Now, I am NOT allowed to modify that file or (this would be much easier!). And here is my form:

  <div class="sidebar-left col-xs-12 col-sm-4">
    <form action="/" method="POST" id="registrantForm">
      <h1>Please Register</h1>
      <input type="text" name="name" id="register-name" placeholder="username" required>
      <input type="email" name="email" id="register-email" placeholder="email" required>
      <input type="submit" value="Submit">
      <div id="form-error" class="error"></div> 
    </form>
  </div>

Here are some things I have tried,

  • detecting the current window.location and if it is '/' then redirecting back. This does not work since once you are on the '/' route - you are no longer on an html page so the javascript does not work.

  • toying around with onbeforeunload, but this does not work because I do not have access to the destination route, and realized that even if I did, I would be thwarting the submission if I redirect away from '/' before the submission is complete.

  • pulling the submission of the form out of the html and into JS to try to control the route after the submission(using the onload event), however I have not been able to get the data to post either sending the params as query string or a stringified object:

:

function submit(emailInput, nameInput){
  var params = {
    email: emailInput,
    name: nameInput
  };
  request.open("POST", "http://localhost:9292", true);
  request.send(JSON.stringify(params));
  request.onload(function(){
    window.location.assign('http://localhost:9292/homepage');
  });
}

or not sending params with the request.send() , as it seems to be grabbing it from the url's search query anyways. Both result in the page reloading on submission without a redirect to '\\' , but without the data being saved either.

How do I go about redirecting the user back to the /homepage route while successfully submitting the form data? Is this possible in this set-up?

Probably the simplest way to doing this is to replace the form action with js and just submit the values with js - so then no redirect happens

And that's exactly how it works. So I build some example code to prove it and explain it. (hint: I used jQuery just for convenient you can do this in plain js)

<script type="text/javascript">
    $( document ).ready(function() {
        // submit the from values with js 
        // and clean the input fields 
        // but not submit the form normally
        // that's why false is returned
        $('form').submit(function() {
            // get your form data in a standard URL-encoded notation
            // standard URL-encoded notation
            var data = $('form').serialize();

            // post your data with ajax to the server
            // https://api.jquery.com/jQuery.post/
            // here you would add your on success function
            // to display a message to the user or whatever else
            $.post('/', data);

            // retuning false here prevents the form to get posted
            // https://api.jquery.com/submit/
            return false;
        });
    });
</script>

Side-note the ruby code has much potential to be better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM