Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 260
unbalanced_equation Avatar asked Feb 05 '23 10:02

unbalanced_equation


1 Answers

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>
like image 136
Tulio Faria Avatar answered Feb 08 '23 00:02

Tulio Faria