user2542869 user2542869 - 1 year ago 77
Ajax Question

Getting database info for a django template with ajax

I'm very new to django and ajax, i'm trying to do the following:

  • In my html i have a few "select" elements, and for every "select" there is a button called "view".

  • When I click "view" i want to retrieve database info dependent on the option selected in the "select" corresponding to the clicked "view". This should be done by ajax, and i want to display some of said database info in the html (without refreshing the page obviously).

I understand i should add a onClick event to the buttons, and in there send the selected option info via ajax, what I'm confused about is the following:

  • In such a scenario, should i use GET or POST? And why?

  • What URL do i contact with AJAX? Should i create a special URL that will be used only for this function (and presumably won't be visited by the user in a normal way)?

  • Once I already have the AJAX call, how exactly should i return the database info to the template? I would assume this is somehow done in the view corresponding to the URL i will be calling? Do i somehow use the "success" function in the javascript that calls AJAX?

The most relevant question here i found was this one Django: Get database object value in template using Ajax, but it doesn't clear all of my doubts.

Answer Source

For this particular use case you should use GET. If you're using jQuery, which makes these things really easy you can use $.GET().

Create a view that returns a JsonResponse and contact that with Ajax.

Yes. You'll use the success function in the jQuery GET and the response will contain a JSON serialized output from Django.

You can either build the JSON object yourself, or use a Django serializer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download