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:
- Each time a GET completes, a new line of information should appear on the page.
- If the GET could not be complete, a default info appear on the page.
My idea so far is to do something like this:
- Have my controller performing each GET inside a thread.
- Each time a thread ends, with success or not, I inform the view of the result and render a partial
- I’ll have as many partial as I need (for each GET I must do)
- The first time I load the page I fill in the default info, them I update via AJAX with the successful GET responses
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.
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 arequest.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 theajaxfunction 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.