0

fI'm developing a simple and small search in a Wordpress page using a $_GET variable in the url passed by javascript:

<script>
function pesquisar()
{
    var pesquisar = document.getElementById('termo').value;
    var caminho = document.URL+'&pesquisa='+pesquisar;
    window.location = caminho;
}
</script>

<input type='text' id='termo'>
<input type='button' value='pesquisar' onclick='pesquisar()'>

So, the url to search is: MYURL/?page_id=51&pesquisa=test

Of course, the page_id is variable. If I search again, the URL is going to be: MYURL/?page_id=51&pesquisa=test&pesquisa=new, what is wrong.

How could I get just the MYURL/?page_id=51 using javascript? The window.location.pathname is not what I need.

Thanks.

user2375094
  • 33
  • 1
  • 3
  • 2
    possible duplicate of [How can I get query string values?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values) – maerics Oct 18 '13 at 14:21

4 Answers4

0

Try this hopefully it should work

<script>
function pesquisar()
{
    var pesquisar = document.getElementById('termo').value;
    var caminho = location.protocol + '//' + location.host + location.pathname+'&pesquisa='+pesquisar;
    window.location = caminho;
}
</script>

<input type='text' id='termo'>
<input type='button' value='pesquisar' onclick='pesquisar()'>
Dominic Green
  • 10,142
  • 4
  • 30
  • 34
0

try this.

var a = document.URL;
    var result = a.substr(0, a.indexOf('&'));

Resources:

Community
  • 1
  • 1
Henk Jansen
  • 1,142
  • 8
  • 27
0

Anything that searches naively will be vulnerable to problems like this: What if the URL is:

http://example.com/?pesquisa=test&page_id=51

You need to search for and remove the relevant query parameter:

var caminho = document.URL.replace(/([?&])pesquisa=[^&]+&?/,"$1")+"&pesquisa="+pesquisar;
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

javascript:

<script type="text/javascript">

function get_query_param(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

window.onload = function() {
    if (get_query_param("page_id") != null) {
        alert(window.location.pathname + "?page_id=" + get_query_param('page_id'));
    }
}
</script>

hope that helps.

geevee
  • 5,411
  • 5
  • 30
  • 48