none
Unable to use jquery to perform search with REST API

    Question

  • I have the following code trying to hit the search service through REST API but I'm getting errors like ExecuteOrDelayUntilScriptLoaded is not defined, _spPageContextInfo is undefined also, could you please let me know which reference am I missing here?

    <!DOCTYPE html>
    <head>
        <script src="scripts/jquery-3.3.1.min.js" type="text/javascript"></script>
    </head>

    <body>
        <script>
            $(document).ready(function() {
                ExecuteOrDelayUntilScriptLoaded(getSearchResultsREST('ClientSiteType:ClientPortal* contentclass:STS_Site Region=LAT'));
            });

            function getSearchResultsREST(queryText) {
                var searchUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + queryText + "'";
                var executor = new SP.RequestExecutor(_spPageContextInfo.webAbsoluteUrl);
                executor.executeAsync(
                    {
                        url: searchUrl,
                        method: "GET",
                        headers: { "Accept": "application/json; odata=verbose" },
                        success: SearchResultsSuccess,
                        error: SearchResultsFail
                    }
                );
            }

            function SearchResultsSuccess(data) {
                var jsonObject = JSON.parse(data.body);
                var results = jsonObject.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
                    if (results.length == 0) {
                        $('#related-content-results').text('No data found');
                    }
                    else {
                        var searchResultsHtml = '';
                        $.each(results, function (index, result) {
                            searchResultsHtml += "<a target='_blank' href='" + result.Cells.results[6].Value + "'>" + result.Cells.results[3].Value + "</a> (" + result.Cells.results[10].Value + ")<br />";
                        });
                        $('#related-content-results').html(searchResultsHtml);
                    }
            }
        </script>

        <input type="text" id="txtQuery">
        <input type="button" id="doSearch" class="" value="Perform Search" onclick="getSearchResultsREST(document.getElementById('txtQuery').Value);" >

        <div id="related-content-results"></div>
    </body>


    Carlos M

    Thursday, September 6, 2018 11:18 PM

Answers

  • Hi,

    ExecuteOrDelayUntilScriptLoaded method is used to execute the specified function if the file containing it is loaded; otherwise, adds it to the pending job queue.

    For example:

    ExecuteOrDelayUntilScriptLoaded(function,ScriptFileName);

    To use Search REST API to get query results and display the results on the page, you can try the code below:

    <!DOCTYPE html>
    <head>
        <script src="http://code.jquery.com/jquery-1.11.3.min.js" type="text/javascript"></script>
    </head>
    
    <body>
        <script>
            $(function(){
                getSearchResultsREST('ClientSiteType:ClientPortal* contentclass:STS_Site Region=LAT');
    			$("#doSearch").click(function(){
    				getSearchResultsREST($("#txtQuery").val());
    			});
    			
            });
    
            function getSearchResultsREST(queryText) {
                var searchUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + queryText + "'";
                $.ajax({
    				url: searchUrl,
    				method: "GET",
    				headers: { "Accept": "application/json; odata=verbose" },
    				contentType: "application/json; odata=verbose", 
    				success: SearchResultsSuccess,
    				error: function(error) {  
    					$('#related-content-results').html(JSON.stringify(error));  
    				}  
    			});
            }
    
            function SearchResultsSuccess(data) {
    			var results;  
    			var divHTML = '';
    			if (data.d) {
    				results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
    				if (results.length == 0) {
    					$('#related-content-results').html('No data found');
    				}
    				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);  
    						divHTML += "<div>"+title+"/<div>";
    					}					 
    					
    					$('#related-content-results').html(divHTML);
    				}
    			}
            }
    		
    		function getValueByKey(key, results) {  
    			var postItem = $.grep(results, function(e) {  
    				if (e.Key === key) return e;  
    			})[0].Value;  
    			return postItem;  
    		}  
        </script>
    
        <input type="text" id="txtQuery">
        <input type="button" id="doSearch" value="Perform Search" >
        <div><b>results:</b></div>
        <div id="related-content-results"></div>
    </body>

    Demo: Calling SharePoint Search Using REST From JavaScript

    Best regards,

    Linda Zhang


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Friday, September 7, 2018 9:45 AM
    Moderator

All replies

  • Hi,

    ExecuteOrDelayUntilScriptLoaded method is used to execute the specified function if the file containing it is loaded; otherwise, adds it to the pending job queue.

    For example:

    ExecuteOrDelayUntilScriptLoaded(function,ScriptFileName);

    To use Search REST API to get query results and display the results on the page, you can try the code below:

    <!DOCTYPE html>
    <head>
        <script src="http://code.jquery.com/jquery-1.11.3.min.js" type="text/javascript"></script>
    </head>
    
    <body>
        <script>
            $(function(){
                getSearchResultsREST('ClientSiteType:ClientPortal* contentclass:STS_Site Region=LAT');
    			$("#doSearch").click(function(){
    				getSearchResultsREST($("#txtQuery").val());
    			});
    			
            });
    
            function getSearchResultsREST(queryText) {
                var searchUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + queryText + "'";
                $.ajax({
    				url: searchUrl,
    				method: "GET",
    				headers: { "Accept": "application/json; odata=verbose" },
    				contentType: "application/json; odata=verbose", 
    				success: SearchResultsSuccess,
    				error: function(error) {  
    					$('#related-content-results').html(JSON.stringify(error));  
    				}  
    			});
            }
    
            function SearchResultsSuccess(data) {
    			var results;  
    			var divHTML = '';
    			if (data.d) {
    				results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
    				if (results.length == 0) {
    					$('#related-content-results').html('No data found');
    				}
    				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);  
    						divHTML += "<div>"+title+"/<div>";
    					}					 
    					
    					$('#related-content-results').html(divHTML);
    				}
    			}
            }
    		
    		function getValueByKey(key, results) {  
    			var postItem = $.grep(results, function(e) {  
    				if (e.Key === key) return e;  
    			})[0].Value;  
    			return postItem;  
    		}  
        </script>
    
        <input type="text" id="txtQuery">
        <input type="button" id="doSearch" value="Perform Search" >
        <div><b>results:</b></div>
        <div id="related-content-results"></div>
    </body>

    Demo: Calling SharePoint Search Using REST From JavaScript

    Best regards,

    Linda Zhang


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Friday, September 7, 2018 9:45 AM
    Moderator
  • Thanks for your response, however, using the code you provided I'm still having the error _spPageContextInfo is undefined and is not working, not sure if additional references should be added, could you please give me a hint on this. Thanks.

    Carlos M

    Friday, September 7, 2018 2:53 PM
  • Hi,

    Where and how did you use the script?

    Did you use the script in a SharePoint page?

    It has to be loaded from within a SharePoint context such as a page or a form. It cannot be executed from outside of SharePoint.

    If you are trying to do that from outside of SharePoint, you’d better use CSOM.

    Use CSOM outside of SharePoint:

    https://collab365.community/forum/topics/client-side-object-model-javascript-using-from-external-site-page/

    Use search with CSOM:

    http://www.sharepointpals.com/post/How-to-do-a-KeywordQuery-Search-using-Jquery-in-SharePoint-2013

    Best regards,

    Linda Zhang


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Monday, September 10, 2018 2:41 AM
    Moderator
  • I'm using an HTML page inside my site in Sharepoint, from Sharepoint Designer I created a new page within the site collection, it is as follows http://mysharepointserver:27180/sites/myportal/SitePages/MyRestSearch.html but when running I got the error _spPageContextInfo is undefined

    Am I doing something wrong? Please advise, thanks in advance.


    Carlos M

    Monday, September 10, 2018 4:50 PM
  • Just as an update, I changed the page for an ASPX page instead of HTML and added the following line 

    <form id="form1" runat="server">
    <SharePoint:FormDigest ID="FormDigest1" runat="server"></SharePoint:FormDigest>
    </form>

    and now I'm able to get the _spPageContextInfo.webAbsoluteUrl value.

    In case of any comment please let me know and thanks for your help.


    Carlos M

    Monday, September 10, 2018 9:36 PM
  • Hi,

    We need to use _spPageContextInfo in the .aspx file such as site page, because it needs to reference SharePoint Client library and the formDigest value, check this thread below would be helpful:

    https://stackoverflow.com/questions/34994955/sharepoint-context-info-in-html-page

    Best regards,

    Linda Zhang


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Tuesday, September 11, 2018 1:34 AM
    Moderator
  • Is there any way to send a variable value to the success function SearchResultsSuccess. In the ajax call, the function does not have any parameter but in the definition, it has the parameter data.

    I need to change the value of the searchUrl (query/call) based on a variable 'region', I tried to add an additional parameter but I have an error (data is undefined), what I'd like to accomplish is to perform actions (when success) on the DOM based on the value of the new parameter.

    I tried:

     function getSearchResultsREST(queryText, region) {
                var searchUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + queryText + "'";
                $.ajax({
    url: searchUrl,
    method: "GET",
    headers: { "Accept": "application/json; odata=verbose" },
    contentType: "application/json; odata=verbose", 
    success: SearchResultsSuccess(data, region),
    error: function(error) {  
    $('#related-content-results').html(JSON.stringify(error));  
    }  
    });
            }

     

     function SearchResultsSuccess(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('No data found');
    }
    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);  
    divHTML += "<div>"+title+"/<div>";
    }

    if (region == "LA") {

    // Set values for LA
         $('#related-content-resultsLA').html(divHTML);

                                             } else {

                                                 $('#related-content-resultsDR').html(divHTML);

                                             }

      }

    }
            }

    Is this a correct approach to do it? Any help would be appreciated, thanks in advance.


    Carlos M

    Wednesday, September 12, 2018 12:23 AM
  • Hi,

    Try the following code:

    function getSearchResultsREST(queryText,region) {
    
                    var searchUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + queryText + "'";
    
                    $.ajax({
    
                                    url: searchUrl,
    
                                    method: "GET",
    
                                    headers: { "Accept": "application/json; odata=verbose" },
    
                                    contentType: "application/json; odata=verbose",
    
                                    success: function(data) {
    
                                                    SearchResultsSuccess(data,region);
    
                                    },                            
    
                                    error: function(error) { 
    
                                                    $('#related-content-results').html(JSON.stringify(error)); 
    
                                    } 
    
                    });
    
    }
    
    function SearchResultsSuccess(data,region) {
    
                    //code
    
    }


    Best regards,

    Linda Zhang


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Thursday, September 13, 2018 1:36 AM
    Moderator
  • Great, thanks so much.

    Carlos M

    Thursday, September 13, 2018 2:17 PM