Search code examples
jqueryajaxjquery-mobilejquery-mobile-ajax

Return a result after ajax call


I've been trying to write a small function using ajax but I'm really struggling with how to return the result. I've seen some examples on here but I've not managed to apply them to my code...

//function to detect bespoke page
function PageR(iURL) {
  var theLink;
   $.ajax({
      url: './BSK_'+iURL+'.php', //look to see if bespoke page exists
      success: function(data){
        theLink = ('./BSK_'+iURL+'.php'); //if it does display that page
      },
      error: function(data){
          theLink = ('./'+iURL+'.php'); //if it doesn't display the standard page
      },

    }); //end $.ajax
    return theLink;
};

I want to be able to return theLinkto store it as a variable to do something like the below...

function Nav() {
  var theLink = PageR(nav_newCust);
  $.mobile.changePage(theLink);
};

Please help!!


Solution

  • Why don't you try something like this:

    //function to detect bespoke page
    function PageR(iURL, callback) {
      var theLink;
       $.ajax({
          url: './BSK_'+iURL+'.php', //look to see if bespoke page exists
          success: function(data){
            theLink = ('./BSK_'+iURL+'.php'); //if it does display that page
          },
          error: function(data){
              theLink = ('./'+iURL+'.php'); //if it doesn't display the standard page
          },
          complete: function(){
             callback(theLink);
          }
        }); //end $.ajax
    };
    
    function Nav() {
      PageR(nav_newCust, $.mobile.changePage);
    };