I have this form
in index.html
and two submit button on clicking on one button named .graph-btn
I m using jquery and ajax to send data from form
to Django.
Code:
index.html
<form action="{% url 'Graph' %}" method="post">
{% csrf_token %}
<table class="table table-striped table-dark" cellspacing="0">
<thead class="bg-info">
<tr>
<th>Company's Symbol</th>
<th>Current Price</th>
<th>View Current chart</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for a,b in stocks %}
<tr>
<th scope="row" class="comp_name">{{ a }}</th>
<td>{{ b }}</td>
<td>
<input type="submit" class="btn graph-btn" name="_graph" value="View Graph">
</td>
<td>
<input type="submit" class="btn predict-btn" formaction="{% url 'Graph' %}" name="_predict" value="Predict Closing Price">
</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
<script>
$(".graph-btn").click(function(e) {
var $row = $(this).closest("tr");
var $text = $row.find(".comp_name").text();
var name = $text;
console.log(name);
$.ajax({
type:'POST',
dataType: "json",
url:'{% url 'Graph' %}',
data:{
'text': name,
'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(),
},
success:function(json){
},
error : function(xhr,errmsg,err) {
}
});
});
</script>
here I want to take data from th
row named .comp_name
and pass the data to views.py in Django.
There is problem is Ajax.
views.py
def graph(request):
if request.method == 'POST':
print("testing....")
print(request.body)
print(request.POST.get('text'))
name = request.POST.get('text')
context = {
'name': name,
}
print(context)
return render(request, 'StockPrediction/chart.html')
else:
return render(request, 'StockPrediction/greet.html')
I m using Print statement to check if everything is fine. the problem is that when I click on .graph-btn
it throws me two iterative values. First one is the right but the second one is None
.
here
Help me, please.
2
Answers
you shoudn’t use jquery class selector. use id selector(“#id”). Now it happens because you have more then one button with ‘graph-btn’ class. Just assign IDs to your buttons in for loop ( {% for a,b in stocks %})
if clause must be below
if request.method == 'POST' and request.is_ajax():