ajaxcallback

get data from ajax as an attribute value for callback function


I'm new to ajax. I was trying to find the answer but was not lucky to find the corresponding one. Basically I need to use an ajax to get some data and after that to put this data to the variable that later will be used as an attribute for the callback function with custom code.

This ajax part is just a method of myObject.

So, in the end I need this kind of functionality:

myObject.getData(url, callback(data) {
//my custom code of what I want to do after ajax is complete
});

My code

/*
HERE COMES SOME PROPERTIES AND OTHER METHODS WHICH IS NOT THE CASE
*/

//This is where I'm stuck
var getData = function getFromUrl($url) {
         $.ajax({
                type: 'get',
                url: $url,
                dataType: 'html',
                success: function(html) {
                        $obj = html;//I'm lost on this step!
                            },
        });
};

P.S. I'm trying to find an async way (without using async:false). Hope its possible


Solution

  • First I encountered many problems. My first problem was No Access-Control-Allow-Origin, most websites dont allow you to just scrap get their data for security reasons. Luckily someone already made a proxy: http://cors.io/ . Second problem is that you cant embed http on https, so I cant use jsfiddle to show you this working, it works on my local enviroment. After you get the raw html you have to parse it, you can do it with full regex, or you can power yourself with jquery like I'm doing on this example. What we're doing is checking stackoverflow.com and getting the amount of featured questions with .find(".bounty-indicator-tab").first().html(); But once you have the full html you can get any data you need.

    var getData = function getFromUrl(url) {
        $.ajax({
          url: 'http://cors.io/?' + url,
          crossDomain: true,
          dataType: 'html',
          success: function (html) {
            var match = $(html).find(".bounty-indicator-tab").first().html();
            console.log(match);
            return match;
          },
          error: function(e) {
            console.log('Error: '+e);
          }
        });
    };
    
    url = 'http://stackoverflow.com/';
    data = getData(url);
    //You cant use data yet because its working async