0

I have been struggling for last whole night to find the bug but could not find. My javascript code is not working as it should.

var currCab = 0;
var cabBooked = 0;

function sendMessage(cabId) 
{
    if(cabBooked == 1) {
        return;
    }

    // get data from html page 

    $.post("sendMessage.php",data,
           function(data,status){                  
               $("#status").html(data);
           });
}

function checkBookingStatus()
{
    var data = "bookingId="+$("#bookingId").val();
    $.post("checkBookingStatus.php",data,
           function(data,status){
               // callback here
               var ans = data.indexOf("true");
               if(ans!= -1) {
                   console.log("returning true from checkBookingStatus");
                   $("#simpleStatus").html("Cab booked. You can close tab now");
                   cabBooked = 1;
                   return true;
               } else {
                   console.log("returning false from checkBookingStatus");
                   return false;
               }
           });   
}


function tryCabAlloc()
{
    if(!checkBookingStatus()) {
        if(cabBooked == 1) {
            return;
        } 
        var checkid = document.getElementById("cabId"+currCab);
        if(checkid==null) {
            $("#simpleStatus").html("Cab could not be booked.");
            $("#status").html("No more clients to communicate with.");
        } else {
            var cid = $("#cabId"+currCab).val();
            sendMessage(cid);
            updateTrying(cid); 
            currCab = currCab + 1;
        }
    }
}

$( document ).ready(function() {
    $("#simpleStatus").html("Please wait. The communication is being started...");
    $("#status").html("GCM push initiating ...");

    tryCabAlloc();

    setInterval(function(){
        if(cabBooked==0) {
            tryCabAlloc();
        } else {
            throw '';
        }
    },95000);

});

The code should stop working when the checkBookingStatus returns true and cabBooked is set to 1. But is not stopping at all. I have no idea why.

Divanshu
  • 423
  • 3
  • 12
  • 1
    AJAX is asynchronous. Returning from the callback function doesn't return from `checkBookingStatus()`, because it already returned when the AJAX request was sent. – Barmar Nov 15 '14 at 01:02
  • How to overcome this ? – Divanshu Nov 15 '14 at 01:05
  • Do what you want to do in the callback function, as explained in the duplicate question. – Barmar Nov 15 '14 at 01:06
  • I want if the checkBookingStatus return data containing string true then the script should halt all together. – Divanshu Nov 15 '14 at 01:09
  • Assign `setInterval` to a variable, and the callback function can call `clearInterval()` to stop it. – Barmar Nov 15 '14 at 01:11

1 Answers1

0

if(!checkBookingStatus()) { will continue if it's false, not if it's true per your comment.

AlienWebguy
  • 76,997
  • 17
  • 122
  • 145