Night life challenge: resubmitting form not working after reload

Night life challenge: resubmitting form not working after reload
0.0 0

#1

In this simple app the unauthenticated user searches for restaurants with the city name, and when the user chooses a restaurant, he can click on going but he needs to login with twitter first,

now when the user is back after authentication I want to resubmit the term the user inserted so he won’t have to search again. this is what I tried

form.addEventListener('submit', (e) => {
 e.preventDefault();
 const xhttp = new XMLHttpRequest();
 xhttp.onreadystatechange = function(){

 if(this.readyState == 4 && this.status == 200) {

   //format the data for the user interface
   const businesses = JSON.parse(xhttp.responseText);
   formatData(businesses);

   }

 }
 xhttp.open("post", "http://localhost:3000/api/", true);
 xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 xhttp.send(`location=${input.value}`);

 //save searched term in a session
 sessionStorage.setItem('autosave', input.value);
 sessionStorage.setItem('refreshed', false);
});

//
//if the term is saved and the page is refreshed
//(will happen only when page is refreshed)
if (sessionStorage.getItem("autosave") && sessionStorage.getItem("false") == 'false') {
 //restore the contents of the text field
 input.value = sessionStorage.getItem("autosave");
 //then submit
 document.forms["myForm"].submit();
}else{
 console.log('no item')
};

This works but the problem is when the form is submitted automatically it redirects again to “http://localhost:3000/?location=new+york” which results in data not displaying.

I don’t know how to stop it from doing that.


#2

There are a few ways to do this depending on your set up. I think the best way to do it would be to let the server handle redirection after the user is logged in. You could send your login route an optional query parameter with the URL you want to redirect to. It’s unclear from your description exactly where you want to redirect to or why data isn’t displaying in your case, but I’ll use the URL you’ve written as an example. You would send a request to your twitter login path, ie http://localhost:3000/login/twitter?dest=http://localhost:3000/?location=new+york. Your app handles the login in the usual way, but you make sure that the query param dest is included with every step. When you get the Oauth response from Twitter, you redirect the client to http://localhost:3000/?location=new+york with response.redirect.


#3

thank you for the help, i will try your solution ^^.