0

Before you close this as dupe: It's not the regular var passing here I guess.

I have this function and I'm kinda stuck. I want to return from inside the each of the ajax result:

function isInCat(cat, check) {
    var toReturn;
    var toReturnOutside;

    $.ajax({
        type: 'POST',
        url: 'http://www.mediawiki.org/w/api.php',
        dataType: 'json',
        data: {
            format: 'json',
            action: 'query',
            prop: 'categories',
            titles: 'Category:' + cat
        }
    }).done(function (data) {
        console.log( data);

        var toReturnOutside;
        var res = data["query"]["pages"];

        $.each(res, function (i, item) {
            var inCat = "";
            inCats0 = item.categories[0];
            if (inCats0) {
                var inCat = inCats0.title;
                if (inCat == "Category:" + check) {
                    console.log(cat + " = " + check); // works
                    // return cat;
                    toReturnOutside = cat; // doesn't go outside :(
                    return false; // stop loop
                }
            }
        });
        toReturn = toReturnOutside;
    });
    return toReturn; // "MediaWiki components" 
}

The call:

var catToTest = "Edit",
    parentToTest = "MediaWiki components";

var val = isInCat(catToTest, parentToTest); // "MediaWiki components", returns undefined

if ( val == parentToTest) {
    $("body").append(catToTest + ' is in Category ' + parentCatToTest);
}

The data result:

{
    "batchcomplete": "",
    "query": {
        "pages": {
            "17443": {
                "pageid": 17443,
                "ns": 14,
                "title": "Category:Edit",
                "categories": [
                    {
                        "ns": 14,
                        "title": "Category:MediaWiki components"
                    }
                ]
            }
        }
    }
}

The problem may lay in var res = data["query"]["pages"]; but I cannot access to the deeper levels otherwise :/

Non working jsfiddle: http://jsfiddle.net/zro716Le/ (Access-Control-Allow-Origin). Tesing in Tampermonkey works: http://jsfiddle.net/zro716Le/1/

Martin
  • 2,007
  • 6
  • 28
  • 44
  • 1
    The way you are trying to return the result (or more precisely a subset of it) of an asynchronous function (`$.ajax()`) is not possible - at least not without "removing" the asynchonous part... Hence this is also a dupe of the question Stryner has mentioned. – Andreas Nov 16 '15 at 22:31
  • `async: false` doesn't help much. The function returns undefined. – Martin Nov 16 '15 at 22:35

0 Answers0