Search code examples
jqueryexecution

Stop jQuery function from executing


I want a save function to check if a session is set (using another function) and stop the base function from continuing, but the function seems to continue (not executable below):

//1. Base save function

$("#save").click(function (e) {				
  e.preventDefault();
  //step 0 check if logged in
  checksession();
  console.log("teststop"); //just for testing
  //steps x continue execution of session exists
});

//2. Session check function
function checksession(){	
    $.ajax({ 
	type: "GET",
	url:"xxxx/sessioncheck.php",
	dataType: "text",
	cache: false,
	success: function(data){
	    if(data == "no"){
		return;
            } else {} //continue	
        }
    });
}


Solution

  • let checksession's AJAX success callback be the function that performs the "save" operation (or not)

    //1. Base save function
    
    $("#save").click(function (e) {             
      e.preventDefault();
      //step 0 check if logged in
      checksession();
    });
    
    
    //2. Session check function
    
    function checksession(){    
        $.ajax({ 
        type: "GET",
        url:"xxxx/sessioncheck.php",
        dataType: "text",
        cache: false,
        success: function(data){
                if(data == "no")
                {
                    console.log( "stop" );
                } else {
                    console.log( "continue" ); 
                    doSave();
                }   
            }
        });
    }
    
    
    //3. Perform save operation
    
    function doSave() {
        //
        // proceed with the save operation
        //
    }