Reputation: 29
I am building an auction project and in template I am making an AJAΧ call when form submitted from template to view in order to reload the page without refreshing but something is wrong sometimes. Although call is successful, new values aren't shown all the times although altered in database. When i hit F5 new values are shown.
live-auction-details.html
<form id="bid" >{% csrf_token %}
<input id="auction_id" type="hidden" value="{{ auction.id }}">
<button type="submit">Bid</button>
</form>
<script>
$('#bid').on('submit', function(event){ //bid is the name of the form
$.ajax({
method: 'POST',
url: '{% url 'auction:live-auction-details' auction.id %}',
data: {
auction_id: $('#auction_id').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function(data) {
console.log(data);
}
});
});
views.py
def live_auction_details(request, pk):
try:
auction = Auction.objects.get(id=pk, status=1)
except Auction.DoesNotExist:
raise Http404("auction not found")
if request.method == 'POST':
// update records in database
if request.user.is_authenticated():
# can user bid ?
if request.user.player.credits >= auction.credit_charge:
player_can_bid = True
# is player registered ?
if AuctionPlayers.objects.filter(auction_id=auction, auction_player_id=request.user.player.id):
player_is_registered = True
context = {
'auction': auction,
'player_can_bid': player_can_bid,
'player_is_registered': player_is_registered,
}
return render(request, 'auction/live-auction-details.html', context)
Upvotes: 0
Views: 389
Reputation: 129
What AJAX does is an asynchronous request to the server, and it will send a response depending on whether or not it could complete the action that is required. To update the values, you must do it manually, since it is not something in "real time" so to speak.
If the request had a successful response, then you must update the fields of the view in the success function.
For example:
$.ajax({
method: 'POST',
url: 'your_endpoint',
data: your_data_object
dataType: 'json', // If you are using an API RestFul
success: function(response) {
// Here you have to update your view in order to show the changes
// This is an example code
$("#input").val(response.newValue);
}
});
Upvotes: 2