jquery - JavaScript: JSON Conditional based on user response -
this driving me crazy.
user clicks on button reserve it. ajax returns value based on whether or not reservation successful: reservation successful, clear old reservation, or blocked because reserved it. value returned view , button changes based on user's choices.
i've tried every possible iteration, , won't work. though console.log says value == 1, js won't admit value == 1, , i'm sent 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 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 info 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 button, reverts on refresh $.toast({ heading: "reservation complete!", icon: 'success', stack: 4, hideafter: 2000 }); } if (number == 3) { alert("sorry! has been reserved (maybe refresh browser)") } else { console.log("something wrong. wrong. wrong") } count++; console.log(count) if (count > 3) { location.reload(); }; } }); // end ajax }); });
i've tried using quotes on both ends, json.stringify, , creating var that's identical dictionary. help!
you create
data = {'result': result}
and parse
var number = json.parse(data);
this means data contains {"result": yourvalue}
you can acces number.result
or number['result']
also returning strings in response javascript checking integer values
wiki
Comments
Post a Comment