I’m dealing with the problem I’ve seen some people also struggling. I need some functionality based on Facebook like buttons events. So I catch the event of clicking button and on it call my function with ajax. But on each single click my function is called multiple times, varying from 3 to 8. Problem is that this function creates models that ought to be unique, and because of the instant multiple call – I get multiple objects.
How to prevent this ? I’ve tried setting global var, but without any luck :
def send_submission(request):
global BLOCKED
if BLOCKED == 0:
logging.debug("should be locked")
BLOCKED = 1
(... do something...)
BLOCKED = 0
html = render_page(request)
ajax = simplejson.dumps({
"html": html
}, cls=LazyEncoder)
return HttpResponse(ajax, mimetype='application/javascript')
And the js grabbing the call:
FB.Event.subscribe('edge.create', function(href, widget) {
$.ajax({
type: "POST",
url: "/submissions/add",
data: "href="+href+"&ip={{ IP_ADDRESS }}",
dataType: 'json',
success: function(data){
$("#submissions").html(data["html"])
}
});
return false;
});
I’ve tried locking it with js, but it does not work either.
<script type="text/javascript">
window.fbAsyncInit = function() {
var maxAjaxCallAllowed=1;
var openAjaxCalls = new Array();
function insertHtml(data){
openAjaxCalls.pop();
$(".list-submissions").html(data["html"])
}
FB.init({appId: '161771113844567', status: true, cookie: true, xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
alert("glos");
if(openAjaxCalls.length < maxAjaxCallAllowed){
openAjaxCalls.push(1);
$.ajax({
type: "POST",
url: "{% url register_vote %}",
data: "href="+href+"&ip={{ IP_ADDRESS }}",
dataType: 'json',
success: function(data){
insertHtml(data);
}
});
}
else{
alert('Server call not possible at this time');
}
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
If I am getting your issue correct, I think you should define a global variable in javascript. Say you have a global variable
busywhich should be set once a request is sent and unset when the request is completed.Before every request you should check whether the variable is set and if its set do not send the request again.