Return a result after ajax call

92 Views Asked by At

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!!

2

There are 2 best solutions below

0
tabz100 On BEST ANSWER

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);
};
0
Vlada On

You can not do that in such a way, because you have ajax calls who is non blocking and PageR function always return undefined.

Try this:

function PageR(iURL) {
   $.ajax({
      url: './BSK_'+iURL+'.php',
      success: function(data) {
        $.mobile.changePage ('./BSK_'+iURL+'.php');
      },
      error: function(data){
          $.mobile.changePage ('./'+iURL+'.php');
      },
    });
};