6

I have this url http://localhost:1234/pag1

I want to be like below when I click on the div:

 http://localhost:1234/pag1?fare=standar

and I have an onclick event function:

 <div id="" onclick="addUrl();"> </div>

And the js code:

<script type="text/javascript">
 function addUrl() {
    var url = window.location.href;
    window.location.hash = '?fare=standar';
};
    </script>

This give me this result:

http://localhost:1234/pag1#?fare=standar

And I don't Know how to remove the (#). I only need to add the parameter to the url, without refresh the page.

Suggest me! Thank's.

Esraa_92
  • 1,558
  • 2
  • 21
  • 48

5 Answers5

14

Use window.history.pushState( {} , '', '?fare=standar' );

This should update the url without refresh.

You can also do a bit of reseach on pushState as the implementation can differ.

Ionut Milas
  • 318
  • 1
  • 11
1

window.location.hash always put "#" in url

you can use to push paramter in url by using this function

function setGetParameter(paramName, paramValue)
{
    var url = window.location.href;
    if (url.indexOf(paramName + "=") >= 0)
    {
        var prefix = url.substring(0, url.indexOf(paramName));
        var suffix = url.substring(url.indexOf(paramName));
        suffix = suffix.substring(suffix.indexOf("=") + 1);
        suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
        url = prefix + paramName + "=" + paramValue + suffix;
    }
    else
    {
    if (url.indexOf("?") < 0)
        url += "?" + paramName + "=" + paramValue;
    else
        url += "&" + paramName + "=" + paramValue;
    }
    window.location.href = url;
}

i hope this will helpful to you

1

Try this

HTML

<div onclick="addUrl()"> </div>

Javascript

  <script type="text/javascript">
    function addUrl() {
    var url = window.history.pushState( {} , '', '?fare=standar' );
  </script>

Quick Explanation : When user clicks on div, URL will update without refreshing the page.

Hope this will work for you, thank you :-).

-2

Try this

var myURL = document.location;
document.location = myURL + "?a=parameter";

Or

location.hash = 'a=parameter'

Or without reloading the page

window.history.pushState("object or string", "Title", "new url");

Or without reloading the page

window.history.replaceState(null, null, "/another-new-url");
-3

Why dont you use jQuery? I prepared sample like here in JsFiddle:

$("#clickableDiv").click(function(){
  var url = "http://localhost:1234/pag1";
  var parameter = "fare=standar";
  $("#AppendUrl").text(url+ "?" + parameter);  
});
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
  • Thank you for your answer, but you add the url to a

    , I need to add this to URL without reload the page.

    – Esraa_92 Nov 20 '15 at 09:55
  • I don't understand you. Did you mean Ajax ? Something like this : http://stackoverflow.com/questions/18490026/refresh-reload-the-content-in-div-using-jquery-ajax – ercaguysal Nov 24 '15 at 15:02