jqueryajaxsinatra

Sinatra + Ajax to load dynamic content


I want to create a page with will be filled with dynamic info using Ajax (jQuery). The info will come from various GETs I need to do in other URLs. I'll be using Sinatra + JQuery to to that, but as my WEB experience is almost null and don't have any idea how do to it right. The requisites for this are:

My idea so far is to do something like this:

This does not seem the correct approach, so I'm asking someone that already did something similar or has more experience on this some help.


Solution

  • You start off with a simple get('/'){} route that holds the default message (or any other GET route). Then you have your other GET routes that you want to display on your default route. In Sinatra you can check whether a request is an xhr-request or not with a request.xhr? If you have an xhr request you return a json value to your view, otherwise reject the request or render a view with proper html. This is on your sinatra backend. In your views you can use JQuery or any other JS library or plain JS to handle asynchronous data requests. You can use the ajax function in JQuery to request data from your routes and then add them to your DOM. It's as simple as that :)

    Now you will have to investigate on the JQuery site how to make ajax requests and how to append data to existing DOMs. That's all there is to it.