2

I'm trying to figure out how to pass the URL of a current page via a hidden field so that I can redirect back to that page after the form's input has been handled. I've tried using javascript:location.href, however it looks as though it'll pass that as a literal string.

<input type="url" id="location" name="location" value="javascript:location.href" hidden />

When viewing the page source, I can see that the value of this input box is "javascript:location.href" rather than the page's URL. Any ideas here? Thanks in advance!

4 Answers 4

3

You can access the element in Javascript and change the value there

document.getElementById('location').value = location.href;

Example: http://jsfiddle.net/6zxD5/

Sign up to request clarification or add additional context in comments.

9 Comments

That would be possible, but you would need to put this script on the bottom of the page or it will get called before the DOM tree is ready.
yes, but I actually don't see this as a problem. Separating js from html tags isn't the worst thing to do, if you ask me. :) Unless you're doing angular :D
Okay, if you want that, window.onload=function(){document.getElementById('location').value = location.href;} would be even better.
One doesn't have to wait until window is loaded (including all images etc) in order to query the dom, right?
which of the browsers do you consider "modern"? IE9? And we didn't even specify the constraints for our discussion. We're both right, ok ? :)
|
0

I don't think it works that way. You could just use the onload callback to insert it when the page is completely loaded:

<body onload="document.getElementById('location').value = document.location.href">

Comments

0

If your document containing the form is already a PHP file , you can do

 $yourPath = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];

And in your html you would do

echo '<input type="url" id="location" name="location" value="'.$yourPath.'" hidden />';

Comments

0

You can use JavaScript to set the value of the hidden field:

document.getElementById('location').value = window.location.href;

Example:

https://jsfiddle.net/moogs/mhjh0je3/

Since you also tagged PHP, here's the PHP version:

<input type="hidden" id="location" name="location" value="<?php echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>" />

1 Comment

You missed the dot to concatenate the strings in the echo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.