0

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!

3 Answers 3

2

You create

data = {'result': result} 

And then parse it

var number = JSON.parse(data);

This means data contains {"result": yourvalue}

You can acces it by number.result or number['result']

Also you are returning strings in the response where your javascript is checking for integer values

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I figured out what was confusing - the conditional was working, but I was also receiving the console.log from "else". Any idea why?
You are not using "else if" try that. Your last if is checking for 3 if it is 1 or 2 it will still go in the else, consider using a switch statement.
0

Use typeof() to find what data type is returned and later add the condition check.

 var number = JSON.parse(data);
console.log(typeof(number)) // check this what is the output and add the condition based on it
            if (number == 1 ) {

Comments

0

1) First check your parsed number with typeof() operator.

console.log(typeof(number));

2) If it's an array then try.

number[0] == 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.