How can I pass a parameter to a GET web request without it being visible in the URL? - html

I am building a web application Java Spring MVC, JSPs, and jQuery.
I have a URL like this:
http://myserver/myapp/showuser/55
Which shows the "view user" page (for user id '55').
I also have an "edit user" page and after successful edit, I redirect to the "view user" page by going here:
http://myserver/myapp/showuser/55?successMsg=Successfully edited User.
The "success message" is parsed from the URL parameters and displayed on the screen.
It works well, but ...
QUESTION: How can I pass the "successMsg" value to the GET without making it part of the URL itself?

You can use btoa() and atob() to convert to and from base64 encoding.

For Plain JavaScript Web solution:
You can use History pushState method to do that.
History's state is similar to params but it is hidden from the URL.
To do that, simply:
const state = { successMsg: 'Successfully edited User'};
const title = '';
const url = 'myserver/myapp/showuser/';
history.pushState(state, title, url);
In your Show User page, access the state like
console.log(history.state) // { successMsg: 'Successfully edited User'}

Related

How to make "Pretty" URL after dynamic content load using ajax

I am currently developing a website that will dynamically load the page content using ajax triggered by hash changes.
The code looks like this
$("*").delegate("a", "click", function () {
// Trigger Hash Change
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function () {
let newHash = window.location.hash.substring(1);
$("#main-content").load(newHash + " #ajax-content", function (responseTxt, statusTxt, xhr) {
}).hide().fadeIn();
});
Basically what I am working on now is making the URL look "Pretty", I have modified the .htaccess file to remove the .html extension
So a URL that looks like this
www.example.com/about.html
will become this
www.example.com/about
If I navigate the index (home) "www.example.com" page of the website and then navigate from there to the about page, the URL looks fine. "www.example.com#about" since the server does not display the "index" in the URL.
However, if I navigate straight to the about page like this www.example.com/about, then from the about page to another page, for example, the contact page. I get a URL that looks like this www.example.com/about#contact. When it should look like this www.example.com#contact.
My question is what is the best way to handle this? should I use jquery to redirect all to the index page and then add the hash to load the correct content? or is there some way I can not display the unnecessary part of the URL?
I hope my question was clear, I'm new to the server-side stuff involving the .htaccess file. FOr the ajax stuff I was following this tutorial from CSS tricks
https://css-tricks.com/video-screencasts/85-best-practices-dynamic-content/
You can use history.pushState
window.history.pushState("object or string", "Title", "/new-url");
The url will be www.example.com/new-url
in fact you can get history.state after use this method.
console.log(window.history.state)
output should be "object or string"
You can see the docs here.
Remember to use / to override the entire path.
To do what i think that you want, you can just override the url to / and set the hash.
This is probably not the best way to do this, but I have managed to redirect any page to the home page and then replace the / with the hash value so that the site wont end up wit "messy" URLs.
if(window.location.pathname != "/home.html")
{
window.location.replace("home.html" + window.location.pathname.replace("/", "#"));
}
what happens id the user navigates to "*www.example.com/about*" they will actually be sent to the homepage with the #about.html. So the never end up like this "*www.example.com/about#about*"

Redirect a http request to a website from within an iframe with a Reverse Proxy in front of the site

I am using nginx as a Reverse Proxy in front of a website and intercept download/preview requests for the files stored on the site. The download requests come from within an iframe and if the user is not authorised, I redirect them to the logout page. But this does not take the main page (outside of the iframe) to the logout page. Any idea how to go about this?
If the user is not authorised you may want to send a message from the iframe to its parent. On receiving the message you would then redirect the parent window to the logout page. An example implementation is found here.
However this becomes much harder if you are not able to modify the iframe page's source. Since you are using nginx, one solution would be script injection using the ngx_http_sub_module module. This module replaces one string in the response with another. Note that this module is not included by default, you may need to build nginx with the --with-http_sub_module parameter. See the module page for more information, including an example.
The iframe needs the line:
parent.postMessage( "redirect", "http://www.your-domain.com" );
To inject this with nginx you might try:
location / {
sub_filter '</head>' '<script language="javascript">parent.postMessage( "redirect", "http://www.your-domain.com" );</script></head>';
sub_filter_once on;
}
The parent window would need the corresponding code:
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[ eventMethod ];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
// Listen to message from child window
eventer( messageEvent, function( e ) {
// normally if the message was meant to come from your domain
// you would check e.origin to verify that it's not someone
// sending messages you don't want
if ( e.data = "redirect" ) {
window.location.replace( "your-logout-url" );
}
}, false );
A more advanced solution might include the redirect url in the message; you could then handle the iframe redirecting to different locations.

HTML Form to Remove ?get=info on POST Submit?

I have several pages that are arrived on with valid GET data, such as http://website.com/?id=12345
I have a generic HTML form that is pulled onto many different pages using php's "require" and submits using POST. Regardless of which page this form is located on, it should always submit back to that same page. However, after the form is submitted, I would like the ?id=12345 to be stripped out.
So, for example, if the user is on http://website.com/new.php?id=12345, it should post back to http://website.com/new.php. If the user is on http://website.com/old.php?id=12345, that same form it should post back to old.php
Previously the best solution I found was to style the form as such:
<form action="?" method="POST">
Which will change all links to http://website.com/new.php? or http://website.com/old.php? which is very close, but not perfect.
As it turns out, I finally found the solution to my problem by using JavaScript:
url = location.href;
qindex = url.indexOf("?");
This can pull whatever is on the address bar as a string and find the index of the first ? mark. From there:
if(qindex != -1)
tells me that there is a ? mark
var plainUrl = url.substring(0, qindex);
Can get, as a string, everything up to the ? mark, but not after. Finally:
window.location.replace(plainUrl);
Will rewrite the address bar to the plain URL, not including the ? or whatever comes after, and without redirecting the browser.
Since your page will not undergo any server-side processing, you can achieve what you want via a combination of the following two tricks.
First, change your particular querystring to a hash, which is thereafter directly editable without triggering a page reload:
http://yourdomain.com/page.html#search=value
Then modify such a script as this to do what you want to do, according to the query string passed in.
<script type='text/javascript'>
// grab the raw "querystring"
var query = document.location.hash.substring(1);
// immediately change the hash
document.location.hash = '';
// parse it in some reasonable manner ...
var params = {};
var parts = query.split(/&/);
for (var i in parts) {
var t = part[i].split(/=/);
params[decodeURIComponent(t[0])] = decodeURIComponent(t[1]);
}
// and do whatever you need to with the parsed params
doSearch(params.search);
</script>
now you can delete the query string suffix in the following way:
As detailed elsewhere, namely hide variables passed in URL, it's possible to use JavaScript's History API in modern browsers.
history.replaceState({}, null, "/index.html");
That will cause your URL to appear as /index.html without reloading the page
This little gem is explained in more detail here:
https://developer.mozilla.org/en-US/docs/Web/API/History_API

HTML Forms post redirect

I've got an HTML form that I'm posting to a url successfully. However, I need to have the page be redirected after I've posted the form. I'm not able to use ajax because CORS is not enabled. When I post to the url I'm getting a success message, and a redirect link in json format. This seems much easier than it's proving to be.
What I know is, when I post to the original url, a cookie is created, and when I go to the url that the page is returning, I am an authenticated user. So, it seems that I need to capture that cookie, and then redirect, but I could be off base.
This can be achieved using custom scripting.
The script waits for the input button to be clicked and sets up a listener that checks to see if the div that holds the confirmation text is visible and then sends the user to the destination page.
Add this to the code injection point for the page that holds the form:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
var eventposted=0;
$(document).ready(function(){
$('input.button').click(function() {
window.setInterval(foo, 100);
});
});
function foo(){
if(($(".form-submission-text").is(':visible')) && (eventposted==0)){
window.location = "http://www.something.com/destinationpage";
eventposted=1;
}
}
</script>

How to redirect to a webpage that accepts post requests?

I am working on a project where I need to scrap data in JSOUP and the show as HTML in my webpage and on clicking view more I am forwarding to the scrapped URL, issue is where GET url's are working fine but POST request for aspx are not working as it expects some __EVENTVALIDATION, etc,.. as input in form.
The webpage is kepler.sos.ca.gov, if you click on Corporation Name then enter ESCROW, then submit, some results will come up, which I am able to do in JSOUP, but unable to redirect using javascript:__doPostBack('ctl00$content_placeholder_body$SearchResults1$GridView_SearchResults_Corp','DetailCorp$0').
Please advice.
There is a answer over here : unable to get results from jsoup while giving post request
`Connection.Response response = Jsoup.connect(url)
.method(Connection.Method.GET)
.execute();
Document responseDocument = response.parse();
Map<String, String> loginCookies = response.cookies();
Element eventValidation = responseDocument.select("input[name=__EVENTVALIDATION]").first();
String validationKey = eventValidation.attr("value");
Element viewState = responseDocument.select("input[name=__VIEWSTATE]").first();
String viewStateKey = viewState.attr("value");
response = Jsoup.connect(url)
.cookies(loginCookies)
.data("__EVENTTARGET", "")
.data("__EVENTARGUMENT", "")
.data("__LASTFOCUS", "")
.data("__VIEWSTATE", viewStateKey)
.data("__VIEWSTATEENCRYPTED", "")
.data("__EVENTVALIDATION", validationKey)
.data("ctl00$content_placeholder_body$BusinessSearch1$TextBox_NameSearch", "aaa") // <- search
.data("ctl00$content_placeholder_body$BusinessSearch1$RadioButtonList_SearchType", "Corporation Name")
.data("ctl00$content_placeholder_body$BusinessSearch1$Button_Search", "Search")
.method(Connection.Method.POST)
.followRedirects(true)
.execute();
Document document = response.parse(); //search results
System.out.println(document);`
JSoup is not a browser. It does not interpret JavaScript and you can't fire a POST request through a JavaScript link.
JSoup is however quite capable doing POST requests. To use JSoup here, you need to figure out how the actual request is built by the JavaScript. You then can run the same algorithm coded in Java and create the link and do the POST request.
An easier way of achieving what you want is maybe a switch in technology. You can use selenium for example, which allows to "remote control" a real browser, which should have no problem running the JavaScript of that page.