So, assuming you want to render this on the server (which is the simplest to explain), this is fairly simple.
Give your right sidebar an id
so you can reference it with jQuery like $("#the-id-here");
Using $.get()
, you can do an ajax request to your server. You will need to send the data for what element you're clicking on so django knows what results to return. For practice just make sure you can create a simple django view that you can query with $.get
, and see if you can return a response. For AJAX, you will most likely want either django.http.HttpResponse
or django.http.JsonResponse
.
Once you have your endpoint setup and you've verified that you can access it with AJAX, you need to return some HTML. Create an HTML template in your project. For AJAX requests where I'm not rendering a full page, I like to create a subfolder in my templates directory called components/
or partials/
. You don't have to, but it helps to keep things organized.
For AJAX methods that render a template, I like to use render_to_string. This gives me some freedom about how I want the response to be formatted. For example, if I wanted to return some JSON which includes the HTML as well as some metadata, I could do:
return JsonResponse({
"html": render_to_string("my_template.html", {"data": "abc"}),
"status": "ok"
})
Back in the javascript, after you make your AJAX call you'll have a success callback function. In the callback you will want to update the html of the container with $("#your-element").html(/* response here */)
So to summarize
- Create a container in the HTML with an ID that you can select iwth jQuery
- Create a django view and verify you can do an ajax call to it
- Create your template that will be rendered and sent back
- Render the template using
render_to_string
and JsonResponse
if you need more control over the response.
- In your AJAX success callback, use the response to fill your container with the rendered template.