0

First of all I've read this question which I found very usefull.

I'm trying to detect if an url is responding. If so then use this url and start another function if false then create a new url and start an other function.

I tried to implement the code from the question mentioned above but I found it difficult to incorporate that in my code since I do not understand what he tries to mention with the callback.

So what I have is two functions:

function relatedProducts(relatedUrl){
  $.getJSON(relatedUrl, function(data){
    ......
  });
}
function liveSearch(liveSearchUrl){
  $.getJSON(liveSearchUrl, function(data){
    ......
  });
}

Further I have an variable url and I'm trying to test if that url is responding so not if it is valid.

var url ='apple/i-phone/iphone5';

function urlExists(url, exists){
 $.ajax({
   type: 'HEAD',
   url: url,
   success: function(){

      // what do I have to do here??? 
         Poster is mentioning `callback` but which one??
      },
      error: function(){

      // what do I have to do here??? 
         Poster is mentioning `callback` but which one??
      }
    });
  }

  urlExists(url, function(exists){
    if(true){
     var relatedUrl = ??
     relatedProducts(relatedUrl);
    } else {
     var liveSearchUrl = ??
     liveSearch(liveSearchUrl);
  });

I'm still learning jQuery and I'm pretty confused by the poster and his answer ;)

Any help greatly appreciated.

Community
  • 1
  • 1
Meules
  • 1,349
  • 4
  • 24
  • 71
  • The *callback* is the function that is passed into your AJAX call that will run on the response. `$.getJSON(liveSearchUrl, function(data){` - that `function(data)` is the start of the callback function, and it is executed after the `getJSON` data call has returned. – tymeJV Feb 11 '15 at 14:46
  • @tymeJV: Ok thx, but I know what a callback is only I don't know how the poster in the mentioned post uses it. Do you have any thoughts on that?? – Meules Feb 11 '15 at 14:54

3 Answers3

1

AJAX is asynchronous and so calls to AJAX methods are non-blocking. So you can't expect any results from an AJAX method to be available when the control flow is returned to the caller and subsequent function calls should not rely on the AJAX call having completed.

Simple example:

doSomeStuff($.ajax(...)); //doesn't work

Other example:

var x = false;
$.ajax({
    url: url,
    success: function(){
        x = true;
    }
});
if (x) {
    // probably doesn't work
}

That's where the callback functions come in: You can tell a call to an AJAX method to do some stuff once it is finished. Those are the success and error parameters in your example.

Now for your specific example. I realize you copied most of it from an answer to a similar question, but I see several problems with it, amongst other things your use of if (true), which is not what you want there, so here's my shot at improving that code:

First, we need 2 callbacks instead of one, there's no need to force one method to do what was clearly intended to be handled by 2 different methods.

var successCallback = function() {
  var relatedUrl = '' // see note below code block
  relatedProducts(relatedUrl);
}    
var errorCallback = function() {
  var liveSearchUrl = ''// see note below code block
  liveSearch(liveSearchUrl);
}

Next, let's change your urlExists

function urlExists(url, sCallb, eCallb){
  $.ajax({
    type: 'HEAD',
    url: url,
    success: sCallb,
    error: eCallb
  });
}

And finally, this is how you put those pieces together:

var url ='apple/i-phone/iphone5';
urlExists(url,successCallback,errorCallback);

Some notes:

If you want relatedUrl and liveSearchUrl to be the same URL that was used for the ajax call, let me know and I'll change my example accordingly. If not, just put the url you want to use inside the quotes.

Of course, urlExists is a wrapper that's not even needed, you could use your url and the callbacks directly in the AJAX call, but this way it's much cleaner to look at, easier to understand and far more reusable.

This code will execute errorCallback for ANY error, and successCallback if no error occurred. This may actually not be what you want, especially if you consider that AFAIK 3xx status codes are considered an error. To get much finer control, you can define callbacks for each status code, or just for some of them, if you want I can update my example, let me know.

mmgross
  • 3,064
  • 1
  • 23
  • 32
0

Callback is nothing but the value returned by a function.

When OP states callback, in the explanation of ans, he is referencing the address of return value.

For example: In var a = '10' a is the address and 10 is the value stored in it.

Now consider a function b() which returns some value:

function b(){
var a ='a';
return a;
}

var something = b(); // here **something** can be seen as callback of b()

Now coming to your point when OP uses the word callback in this code he is referring nothing but a variable. You can replace the word callback with any work like test, abc and it will still produce the same result.

Hope this helps

Community
  • 1
  • 1
Nishanth Matha
  • 5,993
  • 2
  • 19
  • 28
0

Please check this.It same like nob.

var callback  =  function (x){ 
        if(x)
            alert ("You can make real call to this url"); 
        else
            alert ("Somthing worng");
        };

$.ajax({
        type: 'HEAD',
        url: "/echo/json",
        success: function() {
            callback(true);

        },
        error: function() {
             callback(false);
        }            
    });

http://jsfiddle.net/PK76X/152/

Reinder Wit
  • 6,490
  • 1
  • 25
  • 36
Ihtsham Minhas
  • 1,415
  • 1
  • 19
  • 31