Best Practices For Ajax CRUD?

Hi!
I am a total newb, I did a Django course and I am currently building a project on my own to practice what I’ve learned. Right now I am working on a contacts page for a scheduling app where the user can view/ input and edit their contacts. I am loading all of the data into a data table when I first load the page. I am doing all the CRUD within the page with js and ajax. I am curious as to some advice on how to manage updating an existing entry. Specifically I am interested in some thoughts on the best way / ‘correct’ way to fill out a form with the existing contact info for the user to edit.

Currently, when the user clicks on the edit button for an entry I have written a script that brings up a modal with a form and it fills out the form with the existing values for the user to edit. Right now, since I am already loading all the information when the page loads, i am using the templating language to give my script all of the info to fill out this form like so:

onclick=‘EnsembleModalEdit("{{person.first_name}}","{{person.last_name}}","{{person.email}}","{{person.cell_phone}}","{{person.home_phone}}","{{person.assigned_department.id}}")’

This works fine but I am wondering if there is a better way of doing this. Not 100% sure what best practices are for doing something like this. Should I be retrieving the info I need with ajax every-time I want to edit a contact’s info? Or I could create a different modal for each contact when I first load the page? Any ideas?

You’ve got a number of options, none of which that are necessarily better than any other in the absence of a larger context of information regarding the overall architecture of your system.

One of the easiest ways to handle this would be to have your JS / AJAX code call a view, where this view renders the form as html, and returns that html back out to the client. The JS code then uses that html as the dialog box.

Keep in mind that the JavaScript in the browser cannot render the Django template - that work is done by the server when the page is being rendered. So rendering the data values when the page is being rendered isn’t going to work properly. If you edit a contact, and then go back and edit it again, it’s going to be using the original values, not the edited values.

1 Like

Thanks Ken! That makes a lot of sense! I think I will take your advice!