Reputation: 13
I need three dependent drop down menus. When a user selects the first menu (market environment), then I need ajax to send that selection to my view in django so I can query SQL to get a list of currencies and populate the second list. In firebug, I keep getting the following error:
MultiValueDictKeyError at /Tplots/ajax_curr/"'mkt'"
I also notice that my Post is empty so I think something is going wrong with my ajax code and I'm not sure whats wrong. Any help would be great.
HTML
<script type="text/javascript">
$(document).ready(function get_currency(){
$('#id_mkt').on('change', function(e) {
e.preventDefault();
$.ajax({
type:"POST",
url: "/Tplots/ajax_curr/",
datatype: "json",
success: function(data) {
alert(data);
},
error:function(){
alert("failure");
}
})
})
})
</script>
<div align="center">
<h1>Swap Curves</h1>
<form action="{% url 'Tplots:swapFig' %}" method = "post">
{% csrf_token %}
{{form.mkt}}
{{form.curr}}
{{form.horizon}}
<input type = "submit" value="Go To" />
</form>
view.py
@csrf_exempt
def ajax_curr(request):
if request.is_ajax():
selected_mkt = MktEnv.objects.get(mkt=request.POST['mkt'])
#selected_mkt = request.POST.get('mkt','')
conn = pyodbc.connect('abcd')
cursor = conn.cursor()
sql_raw = r'''
select currency from market_env_detail
where mkt_env_id=%s
and idx = 1''' % (selected_mkt)
cursor.execute(sql_raw)
xx = cursor.fetchall()
currencyL = []
for items in xx:
x = str(items[0])
currencyL.append(x)
curr = list(set(currencyL))
json = simplejson.dumps(curr)
print json
return HttpResponse(json, mimetype="application/json")
forms.py
class CurrencyForm(forms.Form):
Env_Choices = [('', '-- Choose a Environment --'), ] + [(m.mkt, m.mkt) for m in MktEnv.objects.all()]
Curr_Choices = [('', '--Choose a Currency --'),]+[(c.curr, c.curr) for c in CurrencyAjax.objects.all()]
Horizon_Choices = [('', '--Choose a Horizon --'),] +[(h.hid, h.hid) for h in HorIdAjax.objects.all()]
mkt = forms.ChoiceField(choices=Env_Choices)
curr = forms.ChoiceField(choices=Curr_Choices)
horizon = forms.ChoiceField(choices=Horizon_Choices)
Edit:
I'm trying to put the data into the second dropdown using this success function but all my values become blank. Don't know why.
success: function(data) {
for(var i =0; i<data.length; i++) {
var item=data[i];
$('#curr').append(
$("<option></option>").val(item.Id).html(item.Name));
}
}
Upvotes: 0
Views: 532
Reputation: 363
You are not sending POST data. You are missing the data
parameter.
var data = $(this).parents('form').serialize();
$.ajax({
type:"POST",
url: "/Tplots/ajax_curr/",
data: data,
datatype: "json",
success: function(data) {
alert(data);
},
error:function(){
alert("failure");
}
})
Upvotes: 1