Changing template without reloading entire page

In an HTML template, I have an interactive map (using google maps API), and when the user clicks on something in the map, I would like to change the information inside of a different

on that page based on what the user clicks. Currently, I’m doing that by submitting a form on that click, which calls the same view (reloading the page), only now fetching different information to populate the context sent to the front end.

I would like to be able to only change the contents of the

without reloading the entire page because when the page reloads, it does not maintain the same map view the user had before. Additionally, I can’t just use javascript because fetching the data requires a database call. Would it be possible to do this?

Yes, you can do this using JavaScript.

Your JavaScript code can issue a request to a URL to get an HTML fragment. When the server returns that fragment to the JavaScript, the JavaScript can then replace the div (or whatever HTML component is supposed to be replaced).

On the server side, you would create a view that renders a template and returns it. A template does not need to be a complete page.

This is actually a fairly common technique used in many places.

2 Likes

I see, got it! I’ll try creating a new view that renders a template extending the original one. Thanks!

Hi! So now I have a function in my views.py details(request): which my form is submitting the action to, and for now just returns an HTTPResponse of <h1>Hello World</h1>. I have also added a “original_path/details/” path in my urls.py.

However, when my form submits (I use action="details/" so I can send the request to that function in the view), it redirects the whole page to the original_path/details/ url rather than staying on original_path/ , and the only thing on my page is <h1>Hello World</h1>. Not sure if I’m supposed to send the action to just “#”, and handle return something else here if I see the certain request, or if using HTTPResponse is causing the page to reload to the new path.

To do the other part of this requires JavaScript. Using the form submit action does a full page refresh. You need to use AJAX to issue the request, receive the result, and replace the component on the page.

2 Likes

jQuery.load() is probably the easiest way to load data asynchronously using a selector, but you can also use any of the jquery ajax methods (get, post, getJSON, ajax, etc.)

Note that load allows you to use a selector to specify what piece of the loaded script you want to load, as in

$("#mydiv").load(location.href + " #mydiv");

Note that this technically does load the whole page and jquery removes everything but what you have selected, but that’s all done internally.