How to remove params from URL after form is submitted? - javascript

When I use the following link in my browser, a record is populated in the form on this page to edit.
http://vcred.dev/#personal/myacademicdetail?record_id=15
When I click 'SAVE' button, record is successfully updated in database and form with updated values is still in front of me. It is OK for me. But I have only one problem after form is posted. In Address bar URL is still same as before post.
http://vcred.dev/#personal/myacademicdetail?record_id=15
But I want short URL without params in address bar after my form is posted like this:
http://vcred.dev/#personal/myacademicdetail
How it is possible using javascript?

Since you are using a hash in the URL, you could do the following in JavaScript:
location.href = location.protocol + "//" +
location.host +
location.pathname +
location.hash.split('?')[0];
This will not cause a page refresh, as described in this Stack Overflow post: How do I, with javascript, change the URL in the browser without loading the new page?

As far as Zend Framework goes, after you save the record use:
$this->_redirect('#personal/myacademicdetail');
This will tell the user's browser to go to the URL.

I'd do it like this, using PHP:
$referer_host = $_SERVER[ "HTTP_HOST" ];
$referer_uri = explode( "?", $_SERVER[ "REQUEST_URI" ] );
$referer = $referer_host . $referer_uri[ 0 ];
I assumed you might want to see also PHP solution as you've mentioned zend-framework as one of your tags.
I'd simply explode URL like this and then use headers for redirect.

Related

Best way to modify URL parameters with js

I trying to modify URL parameters, but I can't find a perfect way.
First I tried with:
window.location.href = window.location.href + '?test';
The problem is, that the page reloads and it is just added to the url.
Then I tried with:
window.location.href = String( window.location.href ).replace( "?test", "" );
This works perfect, the part I want to replace, gets replaced/deleted, but the page reloads every time...
Then I read about:
window.history.pushState( {} , 'test', '?test' );
But this doesn't work somehow...
My aim is to add and replace/delete URL strings, when buttons were clicked to control functions.
E.g.
The URL is http://www.example.com/?showoverlay&?showhint
So for example this shows an overlay and a hint tooltip based on these URL parameters.
When the user closed the overlay, the part "showoverlay" should be removed without a page reload. So the URL is:
http://www.example.com/?showhint
Have you tried using replaceState? It replaces the history without reloading the page and might fit your use case.
window.history.replaceState(data, title [, url ] );
https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_replaceState()_method
If you need to keep other parts of the url, make sure to store it in a separate variable and attach it back in the url.
This is roughly how you can get each part of your URL:
let url = window.location.origin + window.location.pathname + window.location.search
And then you just add it back with
window.history.replaceState({}, '', url + '&yourNewParameters=value')

Sending JavaScript object to other page

When I click on button on my webpage it should redirect me to other page with JavaScript object. I am not able to code for sending java script object with onclick event to other page. Help me in code for sender side page and receiver side page.
Java script object contains array of multiple key value pairs, and I want to send this array to other page.
Example:
data= { {region: "Maharashtra",sector: "Manufacturing",size: "MSME",year: "2008"} and many }
I apologize if my question is not clear.
There are some ways to do this on JS:
Using Cookies
Using QueryString
Using LocalStorage
Note :
Action using above technique only affected on client side only. Except, targeted page sending it into server.
you don't need java script, enough add params to your <a src=""></a>
for example in html:
<a src="www.something.com/something?region=Maharasta&size=MSME"> Link </a>
or you can add params to your url dynamic for example by jQuery:
var params = { fuu:1680, buu:1050 };
var str = '?' + jQuery.param( params );
$( "#myLink" ).attr('src', $('#myLink").attr('src') + str)

Javascript window.location.href not reloading data

I'm in a situation where I have an Ajax function making a call to a remote site, saving data into a database, then I want to refresh the current page to show the new data. The problem is I'm also using tabs, so I need to pass #tab6 with the URL to get the visitor back to the correct tab.
I'm using
window.location.href = '/clientarea.php?action=productdetails&id=<?php echo $_POST['pkgid']; ?>#tab6';
as my refresh code. It does appear to change the URL, since after it runs I can see #tab6 on the end of the URL. The problem is it's not actually doing a real refresh of the page data, because it's not showing the new info that's pulled from the remote server. I can see that data after a real refresh.
The hacky option would be to run the window.location.href code to get the anchor in the URL, followed by location.reload(); to get the new data, but I'd like to avoid that if there is a better way to handle it.
You should change something between ? and #.
E.g. you could add/replace a random value just before #, generated with Math.random():
window.location.href = '/clientarea.php?action=productdetails&id=<?php echo $_POST['pkgid']; ?>&random='+Math.random()+'#tab6';
Try
window.location.reload(true);
And hacky solution for chrome
setTimeout(function(){window.location.reload(true);},100)
Instead of window.location.href use window.location.assign.

Use POST to submit form, but change action?

I'm trying to submit a form with Java, which looks like this:
<form id="bForm" action="/a/b.php" method="POST"></form>
There are no <input type="hidden">, there are not even any <input> at all.
In the source, I see that this form is submitted when I click a link which
executes javascript code like this:
javascript:b(<k>,<v>)
where <k> and <v> is some key and value consisting of some numbers.
Now, the function b() in the source is this:
function b(value, key) {
var form = document.getElementById('bForm');
form.action = '/b/user/' + key + '/' + value + '.txt';
form.submit();
}
What I'm trying to receive is the .txt file send as response, but trying to directly open
http://<url>.com/b/user/<key>/<value>.txt
in a browser does not get me the .txt file, but a message saying it has to be accessed by using the POST method.
Now, I read about how to send requests via POST (also from trying to find a
solution here) and think I understood most. Still, I only read about mostly everything today, including what forms are, so excuse me if the solution is obvious.
The problem I have here is that there are no parameters I can pass to "let the URL know" which action to do upon submitting the form.
Now as I can probably not change the action of the form, what do I do?
Can I somehow "connect" to the URL which leads to the .txt file via "POST"?
Or do I need to execute the javascript somehow, and if so how?
Edit: I have solved the problem now, not sure if my explanation was not good enough, but the solution seemed pretty simple, I just didnt know enough about forms.
So, action=#myurl# means that the form is submitted to the #myurl#, not to the current page. And, although the target URL seems to point to some file which cannot do anything with the submitted form, this is not right. In fact, it points to a script, but the script is "hidden" in a way that we only see the path to the file we want to download in the URL.
So, I just did this:
URL url = new URL("http://myurl.com/b/user/" + key + "/" + value + ".txt");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
//set User-Agent, Cookie, etc. properties here
c.setRequestMethod("POST");
c.setInstanceFollowRedirects(false); //not sure if this is needed
InputStream in = c.getInputStream(); //this submits the parameter-less form
//now I can get the response with this stream, i.e. read & save the .txt file
All tested and running complete code now, so it works for sure.

hide variables passed in URL

We've been working on a web application and we've just about got it finished up, but there's one thing that bothering us (although by no means is it going to stop production.)
When we call one of the pages (index.html), we sometimes have to pass it a variable in the URL (searchid). So we get a page like http://domain.com/index.html?searchid=string.
We'd ideally like to not show the ?searchid=string, but I'm not sure how we'd do that.
My group doesn't own the index.html page (but we are working with the group that does), so I don't know how much we'd be able to do with anything like .htaccess or similar.
I was thinking about POSTing the variable, but I don't know how to receive it with just HTML and jQuery. Another person in my group thought that after the page loaded we could remove it from the URL, but I assume we would need a page refresh which would then lose the data anyway.
I'm trying to avoid XY problem where the problem is X and I ask about Y, so what's the right way to remove the variable from the URL?
You can use the History API, but it does require a modern browser
history.replaceState({}, null, "/index.html");
That will cause your URL to appear as /index.html without reloading the page
More information here:
Manipulated the browser history
Your question seems to indicate that the target page is not and will not be powered by some server-side script. If that's the case, I'd suggest changing the querystring to a hash, which has the advantage of being directly editable without triggering a page-load:
http://yourdomain.com/page.html#search=value
<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>
Though, it would be better to get some server-side scripting involved here.
It's possible to rewrite the URL using JavaScript's history API. History.js is a library that does this very well.
That being said, I don't think there's any need for removing the query-string from the URL, unless you're dynamically changing the contents of the page to make the current query-string irrelevant.
You could post the data, then let the server include the posted data in the page, e.g.:
echo "<script> post_data = ".json_encode($_POST)." </script>";
This works cross-browser.

Categories

Resources