How to update the dictionary in django templates using Ajax?

Is it possible to update the dictionary or list on my template using an ajax call?

Here is an example:

<div id="#loop">
    {% for item in items %}
        <li>{{ item }}</li>
    {% endfor %}
<a href="backEndSomething/">Add</a>

How can i update the variable ‘items’ without refreshing the page, if the variable is already updated in the back-end when i clicked the link (“Add”). So in my ajax call, i will not have to use appending new html syntax but instead to update the variable only and automatically update the html code aswell.

Because appending html files seems like a lot of work to do.

You can’t :slight_smile:. The items variable lives on the server side. But you could fetch the list from /api/items/if the backend is already updated and then change your page based on the new data.

1 Like

So having a code like this is normal in ajax?

That is what i did just to apply ajax, its like creating another web page :frowning:

No, the typical way of doing this is to isolate that chunk of the template into its own file. You then create a view that renders just that chunk and returns it as html back to the browser.

1 Like

Can you explain how is it done? Just a simple illustration of the concept. Thank you!

How will i pass the data response coming from the success method in ajax to template file?

That’s not quite the idea.

You have some button that performs an action - starting the AJAX process.

That action results in some URL being invoked. That URL, instead of returning data as a JSON data structure, returns HTML instead.

Your success function then injects that HTML into the page.

1 Like