I have working javascript in my Django code. The Javascript updates a field by fetching the field and passing the data as json to a view. Then it updates this field in the DB. The html contains a table and every time someone fills a form out a new row in the table is created.
Problem: It doesn't work when I use For Loops in my html code.
What do I need to add to my javascript to get it to accept the code changes one at a time?
Error: Unexpected Identifier: let autosaveTimer;
. . .
<td>
<form action=" method='post' ">
{%csrf_token%}
<textarea name="cust_notes" maxlength="1000" required="" id="cust_notes"
class="form-control" value="">{{ x.cust_notes }}
</textarea>
</form>
</td>
. . . .
<script>
const customerNoteInput = document.querySelector('#cust_notes');
const notesEndpointURL = '/customers/notes/'
const customerId = {{note.user_cust_id}}
let autosaveTimer;
customerNoteInput.addEventListener('input', () => {
clearTimeout(autosaveTimer);
autosaveTimer = setTimeout(autosaveNote, 2000);
})
function autosaveNote() {
let noteText = customerNoteInput.value
let data = {
'user_cust_id': customerId,
'cust_notes': noteText,
}
// Fetch API
fetch(notesEndpointURL, {
method: 'post',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{csrf_token}}',
},
body: JSON.stringify(data)
})
.then(response => {
if (response.status == 200) {
console.log('Success! Response was 200!')
}
return response.json()
})
.then(data => {
console.log(data)
})
.catch(error => {
console.error('Error: ', error)
})
console.log('Note autosaved:', customerNoteInput.value);
}
</script>
def customer_note_endpoint(request):
if request.method == 'POST':
# When receiving json from Fetch API or "ajax", you get the data from request.body
# To convert that json data into Python, import json and wrap request.body with json.loads
data = json.loads(request.body)
user_cust_id = int(data['user_cust_id'])
customer_note_text = data['cust_notes']
print('Note text:', customer_note_text)
# Get user
note = Note.objects.get(user_cust_id=user_cust_id)
# Update their note text
print('Old note text:', note.cust_notes)
note.cust_notes = customer_note_text
note.save()
print('New note text:', note.cust_notes)
# Save to the database
note.save()
return JsonResponse({'message': 'Post successful!'})
return JsonResponse({'message': 'INvalid method'}, status=405)