Trouble with Ajax post in Django - javascript

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));
}
}

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");
}
})

Related

jquery can't select unique elements using classes

I'm trying to use ajax on some auto generated html elements from django. I saw that you do this by selecting the instances via the class, but I can't seem to get it working. What do I have wrong here?
javascript
$(document).ready(function() {
$('.fix-button').on('submit', function(event) {
event.preventDefault();
var $issue_id = $(this);
$.ajax({
url: '{% url "fix_issue" %}',
type: 'POST',
datatype: 'json',
data: {
issueid: $issue_id.val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success: function (json) {
document.getElementById("fixed_bool").innerHTML = json['result']
console.log(json)
},
error: function (xhr, errmsg, err) {
}
});
});
});
html
<button class = "fix-button" value = "{{ issue.id }}">Fix</button>
views.py
def FixView(request):
if request.POST.get('action') == 'post':
result = ''
id = int(request.POST.get('issueid'))
issue = get_object_or_404(Issue, id=id)
if issue.fixed == False:
issue.fixed = True
result = str(issue.fixed)
issue.save()
else:
issue.fixed = False
result = str(issue.fixed)
issue.save()
return JsonResponse({'result': result, })
You're trying to add an eventlistener to essentially, a list, instead of a single element.
Try using the .each() method after grabbing the element.
https://api.jquery.com/each/
The backend was actually working, but the label that switches between true and false was the thing that wasn't properly updating. To fix this, I added unique id's to the label, <span id = "{{ issue.id }}">{{ issue.fixed }}</span> and got the unique id using
var issue_id = $(this).val()
document.getElementById(issue_id).innerHTML = json['result']

HTML value passed to WebService is showing NULL

I have a AJAX Web Serice that runs an SQL statment, which works.
I am trying to take an HTML value from my web page and use it as an additional variable in my query.
Here is how I am capturing that variable on my web page.
<div style="margin-left:0px">
<label>Enter Number here: </label><br>
<input type= text id="demo">
</div>
...and this is my Web Service call.
//Generate code
function Generate() {
var myGrid = $('#jqquotes'),
selectedRowId = myGrid.jqGrid('getGridParam', 'selrow');
docid = myGrid.jqGrid('getCell', selectedRowId, 'docid');
document.getElementById("demo").innerHTML = document.getElementById("demo").value;
alert(document.getElementById("demo").value);
var quotenum = document.getElementById("demo".value);
if (confirm('Are you sure you want to generate a quote?')) {
$.ajax({
url: '/WebService1.asmx/Generate',
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "GET",
data: { docid: docid, quotenum: JSON.stringify(quotenum) },
success: function () {
//Get selected
var grid = $("#jqquotes");
var rowKey = grid.jqGrid('getGridParam', "selrow");
//Refresh grid
$('#jqquotes').trigger('reloadGrid');
//Set Selected
setTimeout(function () {
jQuery('#jqquotes').jqGrid('setSelection', rowKey);
}, 200);
}
});
} else {
return false
}
}
The alert box correct displays the HTML value from the box id "Demo"
But the WebService fails, saying the value is NULL, JSON reponse is:
Message "The parameterized query '(#docid nvarchar(5),#quotenum nvarchar(4000))UPDATE [dbo].[quote' expects the parameter '#quotenum', which was not supplied."
...and the GET URL shows the value as NULL
https://localhost:44338/WebService1.asmx/Generate?docid=10146&quotenum=null
Any help greatly appreciated.
I think the problem is here:
var quotenum = document.getElementById("demo".value);
This should be
var quotenum = document.getElementById("demo").value;
as in the line above it.

Use Ajax response script into a Django HttpResponse

I am trying to pass the ajax response obtained from view to the template using HttpResponse but I don't have any idea, how to do that?
view.py
analyzer=SentimentIntensityAnalyzer()
def index(request):
return render(request, "gui/index.html")
#csrf_exempt
def output(request):
sentences = request.POST.get('name',None)
senti = analyzer.polarity_scores(sentences)
context_dict = {'sentiment': senti}
return render(request,"gui/index.html", context = context_dict
I want the senti to be printed after the score on the page but I am unable to obtain it.
template file
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<form action = Post>
Enter Sentence:<input id = "name" type = "text" name = "EnterSentence" encoding = "utf-8"><br>
<input onclick = "testfunction()" type = "button" value = "Submit" >
</form>
<div><strong>Score is {{ sentiment }}</strong></div>
</body>
<script>
var testfunction = () => {
var test = document.getElementById("name").value
console.log(test)
$.ajax({
type: "POST",
dataType: "json",
url: 'output/',
data:{
csrfmiddlewaretoken: '{{ csrf_token }}',
'name': test
},
success: function(response) {
console.log("Succesful return firm ajax call");
},
error: function(result){
console.log("Failure");
}
});
}
</script>
</html>
In your view.py return render(request,"gui/index.html", context = context_dict code is missing ending paranthesis.
This is the correct order of jQuery ajax:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Your success and error fields are inside of data.
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
This is an example of how to use .html method of ajax jquery. You can adjust for your own.
Additionally, use below code to loop through response:
$.each( data, function( key, val ) {
HTMLString += <li id='" + key + "'>" + val + "</li>
});
and this should be inside of the function of success and then pass HTMLString into .html method
To make it clearer how to $.each works:
var numbers = [1, 2, 3, 4, 5, 6];
$.each(numbers , function (index, value){
console.log(index + ':' + value);
});

ajax get wrong value

I used ajax for my current project with laravel and i try to pass value of textbox using ajax but it pass R every time, even if i pass the wrong variable with ajax. my code is as below
<div class="form-group">
<label for="">Total Amount</label>
<input type="text" class="form-control" id="total_amount" value="123" name="total">
</div>
javascript code
$("#id_label_multiple").on('change', function () {
var list = $("#id_label_multiple").val();
var total = $("#total_amount").val();
console.log()
$.ajax({
url: "{{ action('hkcontroller#getTotal') }}",
data: {
lists: list, total: total, "_token": "{{ csrf_token() }}"
},
type: "POST",
success: function (data) {
$('#msg').html('Received ' + data + ' stones form exporter successfully!')
console.log(data);
}
});
});
laravel method
public function getTotal(Request $request)
{
$list = #$request['lists'];
$total = #request['total'];
return $total;
}
varibale list work fine but total always return value R, when it print first time log that time it print correct value in console, but second time in success function of ajax it print always R. where i made mistake??
Change this:
$total = #request['total'];
to this:
$total = #$request['total'];
^
Try like below:
$("#id_label_multiple").on('change', function () {
var list = $("#id_label_multiple").val();
var total = $("#total_amount").val();
console.log()
$.ajax({
url: "{{ action('hkcontroller#getTotal') }}",
data: "lists="+list+"&total="+total+"&_token={{ csrf_token()}}",
type: "POST",
success: function (data) {
$('#msg').html('Received ' + data + ' stones form exporter successfully!')
console.log(data);
}
});
});

Ajax post multiple variables via loop?

I am trying to post multiple variables from the already dynamically create-able "username" id's such as "username1", "username2", etc. I'm looking for a way to dynamically send these into ONE ajax post request. My problem is mainly with the data parameter.
var numOfInputs = $('input').length;
$.ajax({
type: "POST",
url: "ajax.php",
// need way to dynamically pass more of these via numOfInputs.
data: ({username1 : $('#username1').val()}),
success: function(msg){
$('#statuses').html(msg);
}
});
requested html:
<input type="text" id="username1"></input><button id="add">+</button><button id="check">Check</button>
<div id="added-fields">
</div>
<div id="statuses">
</div>
var data = {};
for (var i = 1; i <= numOfInputs; i++) {
data["username" + i] = $("#username" + i).val();
}
$.ajax(
...
data: data,
....
)
Well you can say:
$.ajax({
type: "POST",
url: "ajax.php",
data: $('input').map(function() {
var o = {};
o[this.id] = this.value;
return o;
});
...

Categories

Resources