This is driving me crazy.
User clicks on a button to reserve it. AJAX returns a value based on whether or not the reservation was successful: Reservation successful, clear an old reservation, or blocked because someone already reserved it. That value is returned to the view and the button changes based on the user's choices.
I've tried every possible iteration, and it won't work. Even though console.log says value == 1, JS won't admit that value == 1, and I'm sent to my error message every time.
views.py
@ensure_csrf_cookie
def reserve(request):
if request.is_ajax():
pk = request.POST['pk']
slot = Event.objects.get(pk=pk)
user = request.user
if slot.is_reserved == True:
if user == slot.teacher:
slot.is_reserved = False
slot.teacher = None
slot.save()
result = "1"
else:
result = "3"
else:
slot.is_reserved = True
slot.teacher = user
slot.save()
result = "2"
data = {'result': result}
return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder))
//main.js
$( document ).ready(function() {
var count = 0; //to reload the page
console.log( 'ready!' + count ); //Sanity check
$( 'button' ).click(function() {
var pk = this.id
var user = $( 'button' ).attr("user")
$.ajax({
url: "/reserve/",
type: "POST", //Send the info to view
data: { pk : pk},
success: function(data) {
var number = JSON.parse(data);
if (number == 1 ) {
$(this).toggleClass( "free reserved" );
$.toast({
heading: "Reservation Clear!",
icon: 'success',
stack: 4,
hideAfter: 2000,
bgColor: '#003366'
});
}
if (number == 2) {
$(this).toggleClass( "free reserved" );
$("div.tchr").html(user); //Send user info to button, reverts on refresh
$.toast({
heading: "Reservation Complete!",
icon: 'success',
stack: 4,
hideAfter: 2000
});
}
if (number == 3) {
alert("Sorry! This has already been reserved (maybe refresh your browser)")
}
else {
console.log("Something is wrong. Something is wrong. Something is wrong")
}
count++;
console.log(count)
if (count > 3) {
location.reload();
};
}
}); // End AJAX
});
});
I've tried using quotes on both ends, JSON.Stringify, and even creating a var that's identical to the dictionary. Help!