Using Javascript to emphasize Ajax Response

I am faced with a challenge of highlighting specific words within text received from an ajax response, before generating HTML code and inserting it into the DOM. At the moment, I am utilizing the following code snippet:

function highlightWords(line, word, htmltag) {
    var tag = htmltag || ["<b>", "</b>"];
    var regex = new RegExp('(' + preg_quote(word) + ')', 'gi');
    return line.replace(regex, tag[0] + "$1" + tag[1]);
}

function preg_quote(str) {
    return (str + '').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<<>>\|\:])/g, "\\$1");
}

However, this method does not allow for highlighting individual words if the query is a phrase like sit behind. It highlights the entire phrase as one unit rather than each word separately. Additionally, it does not take HTML tags into consideration leading to less aesthetically pleasing results when the query includes a term like span...

I have come across different libraries that handle text highlighting more effectively, such as or

However, these libraries tend to focus on highlighting existing content within the DOM.

My scenario involves receiving an ajax response which needs to be converted into HTML using JS before being inserted into the parent container using DOM7 (similar to jQuery). Hence, I prefer to highlight the text before generating the HTMLString and pasting it into the DOM.

Any suggestions?

Answer №1

Utilizing a library is definitely the way to go for this task. I personally recommend using an excellent library called mark.js.

This library can be used independently or with jQuery, giving you great flexibility in implementation.

  1. Initiate the AJAX request.
  2. Inject the string into the DOM.
  3. Invoke the Mark.js API on the loaded content.

Below is a sample code snippet:

document.addEventListener('DOMContentLoaded', getText);

function getText() {
  const headline = document.getElementsByTagName("h1")[0];
  const p = document.getElementsByTagName("p")[0];

  fetch('https://jsonplaceholder.typicode.com/posts/1').
  then(response => response.json()).
  then(json => {
    console.log(json);
    headline.innerHTML = json.title;
    p.innerHTML = json.body;
    addMark('aut facere');
  });
}

function addMark(keyword) {
  var markInstance = new Mark(document.querySelector('.context'));
  var options = {
    separateWordSearch: true
  };
  markInstance.unmark({
    done: function() {
      markInstance.mark(keyword, options);
    },
  });
}
<script src="https://cdn.jsdelivr.net/mark.js/8.6.0/mark.min.js"></script>
<div class="context">
  <h1></h1>
  <p></p>
</div>

Answer №2

My solution for highlighting the response of an ajax request is below:

$.ajax({
    url : url,
    type : 'POST',
    success: function(response) {
        // Implementing Highlight
        let searchTerm = 'word';
        $container = $("#selector");
        $container.show().unhighlight();
        if (searchTerm){
            $container.highlight(searchTerm, {
                done: function() {
                    $container.not(":has(mark)").hide();
                }
            });
        }
    }
});

Answer №3

Important note: Be cautious as this code utilizes DOM7 in accordance with the question

Summary: Rather than adding an entire HTML string to your #container, consider appending normal text sections as text and highlighted elements as separate elements. This approach allows for easy styling customization.

var text // response from ajax call
var strQuery = 'sit behind' // search query 

var queryWords = strQuery.split(' ')
var textWords = text.split(' ')
var bufferNormalWords  = []

textWords.forEach(function (word) {
    if (queryWords.indexOf(word) != -1) { // word found
      var normalWords = bufferNormalWords.splice(0, buffer.length) // clear buffer
      // Your DOM7 logic here
      $$('#container').add('span').text(normalWords.join(' ')) // normal text
      $$('#container').add('span').css('color', 'red').text(word + ' ') // highlight in red          
    }
    else bufferNormalWords.push(word)
})

Avoid converting text to HTMLStrings unnecessarily; simply manipulate the text and create appropriate elements for styling using DOM7.

Answer №4

In the scenario where your ajax response includes HTML, it may be challenging to avoid creating DOM elements initially. The following code effectively accomplishes the task, even if the query involves the presence of span and the ajax results contain <span>.

        function highlightWords(line, word, htmltag) {
            var words = word.split(/\s+/);
            var tag = htmltag || ["<b>", "</b>"];

            var root = document.createElement("div");
            root.innerHTML = line;
            root = _highlightWords(words, tag, root);
            return root.innerHTML;
        }

        // Recursive examination of the generated DOM element
        function _highlightWords(words, htmlTag, el) {
            var children = [];

            el.childNodes.forEach(function(el) {
                if (el.nodeType != 3) { // excluding Text Type
                    var highlighted = _highlightWords(words, htmlTag, el);
                    children.push(highlighted);
                } else {
                    var line = _highlight(el.textContent, words, htmlTag);
                    var span = document.createElement("span");
                    span.innerHTML = line;
                    children.push(span);
                }
            });

            // Clearing the element's HTML contents to add new children
            el.innerHTML = "";
            children.forEach(function (c) { el.appendChild(c)});
            return el;
        }

        // Identifying and highlighting any matching words
        function _highlight(line, words, htmlTag) {
            words.forEach(function(singleWord) {
                if (!!singleWord) {
                    singleWord = htmlEscape(singleWord);
                    line = line.replace(singleWord, htmlTag[0] + singleWord + htmlTag[1]);
                }
            });
            return line;
        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to retrieve JSON data from php script, but able to successfully retrieve it from file.json

This is the function of my PHP testing script: $json = array ( "age" => 5, "name" => "Lee", ); $json = json_encode($json); echo $json; The JSON data is successfully printed out. When I save its content in a file named file.json and read ...

The Problem with AJAX Error Handling Customization

Upon loading my webpage using Code Igniter and PHP, the JSON encoded query is returned successfully with data. I have managed to handle the scenario where no records are found by encoding a response in JSON format. However, I am unsure of how to transmit t ...

Exploring the process of retrieving array elements from an AJAX response transmitted from PHP

Here is an example of jQuery code for an ajax function: $(document).ready(function() { $("#zip_code").keyup(function() { var el = $(this); var module_url = $('#module_url').val(); if (el.val().length === 5) { $.ajax({ ...

Formatting HTTP HTML response in Vue.js can be achieved by utilizing various methods and techniques

I have a WordPress site and I'm trying to fetch a specific post by its ID. Currently, the content is being displayed successfully, but it's also showing HTML tags in the main output. Here is an example: https://i.stack.imgur.com/f3pdq.png Code ...

Converting 2D pixel art into 3D coordinates with ThreeJS

Attempting to display a cube generated in ThreeJS on an HTML canvas at a specific location has been quite challenging. The location is defined in pixels, for example (100,200). Unfortunately, the process of converting these pixel values into ThreeJS coord ...

Effective implementation of the useReducer hook across various React components to manage form state

My current project is proving to be quite challenging as I navigate through the step-by-step instructions provided. Initially, I was tasked with creating a BookingForm.js component that houses a form for my app. The requirement was to utilize the "useEffec ...

The action of POSTing to the api/signup endpoint is

Currently delving into the MEAN stack, I have successfully created a signup api. However, when testing it using POSTMAN, I encountered an unexpected error stating that it cannot POST to api/signup. Here is a snapshot of the error: Error Screenshot This ...

The mistake is indicating the npm title of a package that is not present

https://i.sstatic.net/5bywN.png An issue has arisen - the module cannot be found, even though such a module does not actually exist. The correct module name should be babel-plugin-proposal-class-properties (and the error is showing as 'babel-plugin-t ...

Generate a highcharts graph by utilizing AJAX and JSON data

I'm currently working on a website project that involves utilizing the Highcharts library to showcase a single line series chart. To obtain historical financial data, I have implemented AJAX to fetch information from yahoo finance using their YQL. Su ...

The issue of variable being undefined in JSON for JavaScript and Python

Consider a scenario where you have the following JSON object (remove the semicolon for python): values = { a: 1, b: { c: 2, d: { e: 3 } }, f: 4, g: 5 }; When attempting to print values in JavaScript, it will work pr ...

Currently waiting for the $resolved property of the AngularJs service

Here's a straightforward issue with what I hope is an equally simple solution. I've set up multiple services for handling CRUD operations with tags. myApp.factory('GetTags', ['$resource', function ($resource) { return $re ...

Creating a dynamic JSON object and retrieving the response in a JSP for data-driven documents

I am a beginner with the D3 API and I need to create a tree-like structure using a JSON file with hardcoded values. Additionally, I have a servlet that retrieves some values from a database which I want to dynamically convert into JSON in the servlet and s ...

Concealing axis lines within the initial circular grid or opting not to include them

Is there a way to incorporate some whitespace within the center circle of the radar chart? I'm aiming for the axis to commence at 1 radius (the initial circular line) or perhaps have the stoke set to 0 for the primary radius. Any assistance would be g ...

What is the process for utilizing AngularJS's multiple $http calls to retrieve data from a single PHP file?

I'm currently experimenting with multiple AngularJS ajax calls to a single php file in order to retrieve different json data based on the request. Below is the code snippet I am working with: var myApp = angular.module('myApp', []); myApp ...

React - Received an unexpected string containing a template expression with no curly braces present in the string

Currently, I am enrolled in a React tutorial online. I have inputted the code exactly as it was shown on the screen. Strangely, it seems to be working perfectly fine in the video but not when I try it myself. Below is the code snippet: <Link to={&apos ...

What is the process for uploading an HTML input file in segments?

Is it possible to upload the whole file at once like this: myInput.onchange = ({ target }) => { const file = target.files[0]; const formData = new FormData(); formData.append("fileData", file); // ...then I post "formData" ...

What is a way to transfer an Object from one Vue.js component to another without relying on vuex?

Using vue-router in app.vue, I defined the two components as shown below: <div class='app'> <div class='nav'> <router-link to='/a'>to A component</router-link> <router-link to= ...

Phonegap fails to make a successful login Ajax call to Yii

Currently working on my initial phonegap application and facing a login issue. I have an appLogin action in the site controller which successfully logs in if the credentials get validated. However, the ajax call in the app fails to retrieve a response. If ...

OctoberCMS Form submission failure (AJAX handler not located)

I recently created a new component within my plugin directory and added the form HTML to default.htm while also including the component in my partial. However, upon submitting the form, I encountered an error message stating: "AjaxHandler Component:onSend ...

Capturing errors during function declaration in JavaScript

A problem has arisen in the below function definition due to a script error function foo () { try { var bar = function() { ERROR } } catch (exception) { console.debug("exception"); } } foo(); However, th ...