I’m trying to get some AJAX running with Django using jQuery. The problem is that the ID of the element I’m trying to change isn’t set in stone, it’s a Django template variable so it is different for each element in the table, but I want to use AJAX to change that element. I’m passing the dictionary from a Django view to JavaScript via simplejson, the pertinent objects being ID and model (not real variable names, just wanted to make it obvious what I am trying to do). Some pseudo code (third line, wrote it like python because I don’t know how to do this in JavaScript):
var quantity_update = function(msg, elem) {
var response_obj = eval('(' + msg + ')');
var newtotal = document.getElementById("%s, %s"); % (response_obj.id, response_obj.model)
subtotal.innerHTML = "<td>"+response_obj.subtotal+"</td>";
Is something like this possible, and if so how?
Javascript doesn’t have fancy string formatting (%s), but you can use plain string concatenation, just like you can in Python:
You don’t need to worry about the string being generated dinamically. It is still a string after all and getElementById accepts it the same way .
You probably shouldn’t be doing the eval() yourself to parse the JSON. I’m pretty sure you can have JQuery do that for you when you do the AJAX request.