5

I have the following Jquery code, I'm trying to display information in $('.cbs-List').HTML(divHTML); based on the region value. But in the success function, I can't read the value for the region, it states that

'data is undefined'

What is the correct form of passing parameters or values to the success function in this case?

$(document).ready(function() {      
    getSearchResultsREST('LA');
});

function getSearchResultsREST(region) {
    var querySA = 'ClientSiteType:ClientPortal* contentclass:STS_Site Region=LA';
    var queryDR = 'ClientSiteType:ClientPortal* contentclass:STS_Site Region=EM';

        if(region == 'LA') {
            var searchURL = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?queryText='" + querySA + "'";
        } else {
            var searchURL = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?queryText='" + queryDR + "'";
        }

        $.ajax({
            url: searchURL,
            method: "GET",
            headers: {
                "Accept": "application/json; odata=verbose"
            },
            contentType: "application/json; odata=verbose",
            success: SearchResultsOnSuccess(data, region),
            error: function(error) {
                $('#related-content-results').html(JSON.stringify(error));
            }
        });
    }

    function SearchResultsOnSuccess(data, region) {
        var results;
        var divHTML = '';

        if (data.d) {
            results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;

            if(results.length == 0) {
                $('#related-content-results').html('There is No data for the requested query on ' + _spPageContextInfo.webAbsoluteUrl);
            } else {
                for (i=0; i<results.length; i++) {
                    var item = results[i];
                    var itemCell = item.Cells;
                    var itemResults = itemCell.results;

                    // Get values for item result
                    var _title = getValueByKey("Title", itemResults);
                    var _path = getValueByKey("Path", itemResults);

                    divHTML += '<li><a href=' + _path + '>' + _title + '</li>';
                }

                // Display information based on region.

                $('.cbs-List').html(divHTML);

            }
        }
    }
Gaurav joshi
  • 1,743
  • 1
  • 14
  • 28
A Mtz
  • 65
  • 1
  • 6
  • You have to urlencode your attributes: add encodeURIComponent() to searchURL instead of the value itself. – m4gic Sep 11 '18 at 17:36
  • You meant if(region == 'LA') { var searchURL = encodeURIComponent(_spPageContextInfo.webAbsoluteUrl + "/_api/search/query?queryText='" + querySA + "'"); – A Mtz Sep 11 '18 at 17:45
  • I put it into an aswer because of the formatting. – m4gic Sep 11 '18 at 17:56

2 Answers2

4

You have 2 problems, and they're both easy to fix.

  • There's no need to pass region into SearchResultsOnSuccess at all. you can already use it in there because it's defined at a higher scope.
  • In the object you're passing to $.ajax, you're not setting SearchResultsOnSuccess as a callback, you're calling it.

Change the lines:

success: SearchResultsOnSuccess(data, region) => success: SearchResultsOnSuccess

function SearchResultsOnSuccess(data, region) { => function SearchResultsOnSuccess(data) {

and it should work fine.

Edit:

Here's a basic example of how you need to set this up

function search(region) {
    $.ajax({
        url: 'example.com',
        method: 'GET',
        success: successCallback,
    });

    function successCallback(data) {
        console.log(data, region);
    }
}
search('LA');
robinsax
  • 1,195
  • 5
  • 9
  • Yes, it is working but I need to perform some actions on DOM based on that value for 'region' i.e. within the success function I would have if(region == "LA") { $('.cbs-ListLA').html(divHTML); } else { $('.cbs-ListRA').html(divHTML); } and some other changes in DOM – A Mtz Sep 12 '18 at 02:34
  • If I try to use the region variable there I got 'region' is undefined. I got $(document).ready(function() { var region = ""; region = "US"; getSearchResultsREST(region); region = "DE"; getSearchResultsREST(region); }); The property success in ajax call with no parameters and the function SearchResultsOnSuccess(data) but region is not reachable. – A Mtz Sep 12 '18 at 13:23
  • updated my answer with a simplified example of how to use a parameter to the search function inside a success callback. – robinsax Sep 12 '18 at 19:45
1

You have to urlencode the value if it contains = or & or whitespace, or non-ASCII characters.

var querySA = encodeURIComponent('ClientSiteType:ClientPortal* contentclass:STS_Site Region=LA');
var queryDR = encodeURIComponent('ClientSiteType:ClientPortal* contentclass:STS_Site Region=EM');

    if(region == 'LA') {
        var searchURL = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?queryText=" + querySA;
    } else {
        var searchURL = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?queryText=" + queryDR;
    }

And normally you don't have to put your values between apostrophes.

I updated the answer, I hope you will understand me better.

Your problem is NOT the parameter passing IMHO but your server response. You should either:

  • turn on the developer tools and check the XHR requests on the network tab, look for the /_api/search/query... requests and examine the response
  • double check the server side logs/study your search service API documentation how to assemble a proper call
  • use your favourite REST client and play around your service: send there queries and check the responses and check that it matches with your expectation
  • last but not least, you can replace your ajax caller with this quick-and-great one:

$.ajax({
    url: searchURL,
    success: function (response) {
        $('#post').html(response.responseText);
    },
    error: function (jqXHR, exception) {
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        $('#post').html(msg);
    },
});

(of course you should have a <div id="post"><div> somewhere in your page)

Your success function IMHO would get your region if gets called, but it does not, and I hope using one or more of these techniques will help you to see clear.

If you are really sure that you get what you want, you can go furher with passing your second argument, as described here

m4gic
  • 1,461
  • 12
  • 19
  • How does it help to get the value of region on success function? – A Mtz Sep 11 '18 at 18:02
  • It does not help in it. If you pass the queryXX variables to the searchURL in this way, your search API will be able to receive it. For me it seems you have passed the region directly to the success function, but the success function will be called ONLY if your server side was able to process your API request successfully. Have you checked that the response code of the _api/search calls was 2xx? – m4gic Sep 11 '18 at 18:08
  • Well, if I change the success property in ajax call with no parameters as: success: SearchResultsOnSuccess, And the function for success as: function SearchResultsOnSuccess(data) { This way I can see the results and 200 response, but if I include the region as mentioned in my original post I'm getting the error that the 'data' is undefined. – A Mtz Sep 11 '18 at 18:19
  • In this case, you have to check the server logs and figure out how to call your service correctly. – m4gic Sep 11 '18 at 18:25
  • I guess I'm calling the service correctly since I'm getting the information requested but wondering how can I send or use the value in region variable within the success function – A Mtz Sep 11 '18 at 20:08