Reputation: 931
Jquery
$('#id_buysell').on('change', function(){
console.log("buysell");
var $id_buysell = $('#id_buysell').val();
console.log($id_buysell);
$.ajax({
method: "GET",
url: "/myportfolio/add_transaction",
data: { buysell: $id_buysell }
});
});
Views
def add_transaction(request):
if request.method == "GET":
if request.is_ajax():
print("ajax test")
#print(request.GET.get)
print(request.GET.get('coin'))
print(request.GET.get('buysell'))
data = {
'view_buysell': request.GET.get('buysell'),
'view_coin': request.GET.get('coin')
}
form = TransactionForm(user = request.user, coin_price = GetCoin("Bitcoin").price)
return JsonResponse(data)
How do I access that dictionary sent from JsonResponse(data) in views to my jquery file? I have a limited understanding of jquery and front end development in general. I know that this will be sent through a JSON-encoded response, but have not been able to find the right answer when searching.
Upvotes: 2
Views: 640
Reputation: 476659
You perform an AJAX request with $.ajax(..)
, but you never specify what to do in case the request succeeds, and how you should handle the data.
The object you pass to the the $.ajax(..)
call, can contain a success
key, that should contain a function that is called with the response:
$.ajax({
method: "GET",
url: "/myportfolio/add_transaction",
dataType: 'json',
success: function(data, status) {
// do something with data and status
},
data: { buysell: $id_buysell }
});
data
thus contains the data wrapped in the response, and status
the status code of the response.
You can add an error
key as well: a function that is called in case the response returns an error:
$.ajax({
method: "GET",
url: "/myportfolio/add_transaction",
dataType: 'json',
success: function(data, status) {
// do something with data and status
},
error: function(response) {
// do something in case the request returns an error
// for example alert the user that the buy/sell transaction failed
// (by checking response.status, response.responseText, etc.)
},
data: { buysell: $id_buysell }
});
Upvotes: 2