Saturday, July 23, 2016

All possible JSONP ajax calls . How I called them and ... failed :(

Here is example how I used different ways to make the same JSONP cal and failed due to wrong header response "Content-type" : "gzip". I collect all of them here because it will be useful for re-use them in future:
var $jsonp = (function(){
   var that = {};

   that.send = function(src, options) {
     var callback_name = options.callbackName || 'callback',
       on_success = options.onSuccess || function(){},
       on_timeout = options.onTimeout || function(){},
       timeout = options.timeout || 10; // sec

     var timeout_trigger = window.setTimeout(function(){
       window[callback_name] = function(){};
       on_timeout();
     }, timeout * 1000);

     window[callback_name] = function(data){
       window.clearTimeout(timeout_trigger);
       on_success(data);
     }

     var script = document.createElement('script');
     script.type = 'text/javascript';
     script.async = true;
     script.src = src;

     document.getElementsByTagName('head')[0].appendChild(script);
   }

   return that;
 })();

// number 1 attempt failed
function show_pokemons_on_map(my_lat, my_lon)
{
 $.getJSON('//freegeoip.net/json/?callback=?', 
   function(data) {
   console.log(JSON.stringify(data, null, 2));
   my_lat = data.latitude;
   my_lon = data.longitude;
   mapGeneration(my_lat, my_lat);
  });
 
}

// number 2 attempt failed
function show_pokemons_on_map(my_lat, my_lon)
{ 
 $.ajax({
    type: "GET",
    url: '//skiplagged.com/api/pokemon.php?bounds='+(my_lat - 0.02) +',' + (my_lon - 0.02) + ',' + (my_lat + 0.02) +',' + (my_lon + 0.02), //+'&callback=jsonpCallback',
    dataType: 'jsonp',
    jsonpCallback: 'jsonpCallback', // the function to call
 //   jsonp: 'callback', // name of the var specifying the callback in the request
    error: function (xhr, errorType, exception) {
      var errorMessage = exception || xhr.statusText;
      alert("Excep:: " + exception + "Status:: " + xhr.statusText);
    }
  });
}


// number 3 attempt failed
function show_pokemons_on_map(my_lat, my_lon)
{ 
 $jsonp.send('//skiplagged.com/api/pokemon.php?callback=handleStuff&bounds='+(my_lat - 0.02) +',' + (my_lon - 0.02) + ',' + (my_lat + 0.02) +',' + (my_lon + 0.02), {
     callbackName: 'jsonpCallback',
     onSuccess: function(json){
         console.log('success!', json);
     },
     onTimeout: function(){
         console.log('timeout!');
     },
     timeout: 5
 });
}


// number 4 attempt failed
function show_pokemons_on_map(my_lat, my_lon)
{ 
  $.ajax({
   url: '//skiplagged.com/api/pokemon.php?callback=?',
   type: "GET",   
   dataType: 'jsonp',
   data: {
     'bounds': (my_lat - 0.02) +',' + (my_lon - 0.02) + ',' + (my_lat + 0.02) +',' + (my_lon + 0.02)
   },
   success: function(data) {
     console.log(data);
   }
 }); 
 }

No comments: