Forum Discussion

hroppanen's avatar
11 years ago

Fire javascript event after search is completed and there is no search results

Is there a way to fire javascript event after user has made search and there is no search results in SearchPage? I would add a possibility to chat if there is no results.
  • hroppanen's avatar
    11 years ago

    I found a solution. I added the following code to custom component to catch the ajax event, parse the response data and search for the text "No search results found."

    <script>
    $(function() {
    
    	/* Part 1. Check if no results when page is loaded  */
    	if ($('.InfoMessage p').text() === 'No search results found.') {
    		console.log('Show chat');
    	}
    
    	/* Part 2. Ajax call event listener */
    	var _send = XMLHttpRequest.prototype.send;
    	XMLHttpRequest.prototype.send = function() {
    		this.addEventListener("readystatechange", function() {
    			if(this.readyState == 4){
    				var jsonObj = $.parseJSON(this.responseText);
    				if (jsonObj.response.components.length !== 0) {
    					var code = $(jsonObj.response.components[0].content);
    					var resultText = code.find('.InfoMessage p').text();
    					if (resultText === 'No search results found.') {
    						console.log('Show chat');
    					}
    				}
    			}
    		}, false);
    	_send.apply(this, arguments);
    	}
    });
    </script>