Search code examples
javascriptjqueryasynchronouspostreturn

how to use return $.post - undefined is not an object (evaluating 'function().then')


I'd like to return some data from a PHP file using $.post(). The $.post-method is inside an if statement, so it does not return every time the function gets called. Here is the code for better understanding:

function abc() {
    ...
    ...

    function def() {
      if (a === 1) {
          // if a equals 1 it works as expected
          return $.post('file.php', formData, function(result) {}); 
      } else {
          // return $.post(); // returns whole page
    }

    def().then(function(result) { // this should be fired too if nothing returns
        console.log(result);
        ...
    });
} 

Solution

  • There's a couple of ways to address this. Firstly you could amend your logic so that the def() function always makes the AJAX request. You then just need to move the if condition outside of it:

    function abc() {
      // some code...
    
      function def() {
        return $.post('file.php', formData, function(result) {});
      }
    
      if (a === 1) {
        def().then(function(result) {
          console.log(result);
          // some code...
        });
      }
    }
    

    This obviously makes the def() itself rather redundant.

    Another approach is to return an empty, resolved promise from within the else condition. You can use $.when to do that:

    function abc() {
      // some code...
    
      function def() {
        if (a === 1) {
          return $.post('file.php', formData, function(result) {});
        } else {
          return $.when(null);
        }
    
        def().then(function(result) {
          console.log(result);
          // some code...
        });
      }
    }