-3

I have a form on a page that is generated dynamically.

One of the fields is:

<input type="hidden" name="pageURL" id="pageURL" value="" />

I'd like to on page load set that value with the current browsers url using:

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

I can't simply put that php into value="" because that field is generated dynamically. But is there simply javascript or jQuery to load the current page url in the users browser (parameters and all) into a value of an input on a page?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
TechRemarker
  • 2,788
  • 11
  • 37
  • 60
  • 1
    How are you appending the `input` to the DOM? Assuming PHP code is available for use at that point then you can `echo` the `value` as you normally would. – Rory McCrossan Mar 31 '17 at 12:58
  • You just want the URL in an input field? I think http://stackoverflow.com/questions/1034621/get-current-url-in-web-browser would answer that. Then set it, `$('#pageURL').val(...)`. – chris85 Mar 31 '17 at 12:59
  • This should work: `` – Jay Blanchard Mar 31 '17 at 12:59
  • How is the field generated dynamically? Is it generated by PHP or is it added to the DOM by JavaScript after the page has loaded? – Jay Blanchard Mar 31 '17 at 13:04
  • Unfortunately, while simply echoing in value would be quite easy under normal stances, this question would be on doing it remotely since that input is generated dynamically by a plugin that for reasons beyond this text box can't edit directly. However I see a one line solution below that solves it. Thank you for everyone sharing your thoughts. Much appreciated! – TechRemarker Apr 01 '17 at 14:50

2 Answers2

2

you can use jquery to add the url to your input field

$('#pageURL' ).val(window.location.href);

https://jsfiddle.net/r1k7eghj/

U.A.Malik
  • 78
  • 8
0

If I understand well, you want to retrieve the URL parameters using JavaScript. If not please tell me I will turn this as a comment.

Here is the function you need:

function getSearchQuery() {
    // Checking if there is any parameter in the URI.
    if (document.location.search) {
        // Returning the parameters of the URI as an object.
        return document.location.search.substr(1).split("&").reduce((item, part) => {
            part            = part.split("=");
            item[part[0]]   = part[1];
            return item;
        }, {});
    } else {
        // Returning an empty object.
        return {};
    }
}

I hope this is what you were looking for. You just need to change the input value with this function.

chris85
  • 23,846
  • 7
  • 34
  • 51
SmashingQuasar
  • 411
  • 2
  • 13
  • No I wasnt asking for javascript code. I was asking for make custom post types in a way that the slug is not added to the url. – U.A.Malik Sep 08 '17 at 13:33