unbalanced_equation
unbalanced_equation

Reputation: 899

How to implement routing with a single page application build solely using jQuery

Right now when the user inputs a word in the textfield and hits search, the form submits using $.get(). The data(JSON) is fetched from the server and then the UI is updated.

What I want to do is pretty simple:

1) When the form submits, the URL of the browser needs to update (something like search/zyx, zyx is what the user is searching for).

2) when the page is booked into favorites, or clicked as a link from somewhere the page needs to load and then the textfield value have to be 'zyx'. Also the UI needs to show search result of zyx.

This is important to my app because I will be using Google Analytics. So the URL is needed to reflect behaviour. Plus the other issue like back button history. Is this possible using just jQuery or some extremely light libraries build on jQuery. I have searched everywhere and all the solutions I found were using MVC frameworks. Or another solution was to use a templating framework like this one. However my app is way too simple for these solutions.

Upvotes: 4

Views: 17083

Answers (3)

unbalanced_equation
unbalanced_equation

Reputation: 899

Thank you every one. So I ended up using a combination between @Tulio Faria 's answer and @Gabriele Mantovani.

  • To get the search keyword from url I used window.location.hash
  • To update url used history.pushState({id: 'query'}, '', 'some_url_string');
  • Used $(window).on('hashchange',function(){...}) to load page of the current search keyword if either back or forward buttons of browser were clicked

Upvotes: 2

Ilphrin
Ilphrin

Reputation: 54

If I understand you want to change the URL of the user when some actions are done. There is an other topic about it HERE, and they use

window.location.replace(url)

Hope it helps you :)

Upvotes: 0

Tulio Faria
Tulio Faria

Reputation: 904

So, the approach you you need is to listen to hash changes in the url and based on this get the current page and render it in a cointainer. Something like this:

<a href="#page2">Go to Page 2</a>
<div class="page-container"></div>
<script>
$(window).on('hashchange',function(){ 
  var page = window.location.hash;
  $.get('pages/'+page+'.html', function(pageContent){
     $('.page-container').html(pageContent);
  })   
});
</script>

Upvotes: 7

Related Questions