Here's is an example for a simple JavaScript AJAX search snippet using the XMLHttpRequest object:

The HTML code:

 

  <h1>Search Results</h1>

  <input type="text" id="searchInput" placeholder="Enter search term">

  <button onclick="search()">Search</button>

  <div id="searchResults"></div>

  <script src="script.js"></script>

 

JavaScript (script.js):

function search() {

  const searchInput = document.getElementById('searchInput').value;

  const searchResultsDiv = document.getElementById('searchResults');

  

  // Create a new XMLHttpRequest object

  const xhr = new XMLHttpRequest();

 

  // Configure the request

  xhr.open('GET', `search.php?q=${encodeURIComponent(searchInput)}`, true);

 

  // Set up a callback function to handle the response

  xhr.onload = function () {

    if (xhr.status === 200) {

      const searchResults = JSON.parse(xhr.responseText);

      let output = '';

 

      // Process the search results

      if (searchResults.length === 0) {

        output = 'No results found.';

      } else {

        output = '<ul>';

        searchResults.forEach((result) => {

          output += `<li>${result}</li>`;

        });

        output += '</ul>';

      }

 

      // Display the results on the page

      searchResultsDiv.innerHTML = output;

    } else {

      // Handle errors

      searchResultsDiv.innerHTML = 'An error occurred while processing the search.';

    }

  };

 

  // Handle network errors

  xhr.onerror = function () {

    searchResultsDiv.innerHTML = 'Network error occurred. Please try again later.';

  };

 

  // Send the request

  xhr.send();

}

 

In this example, we have a simple HTML page with a search input field, a "Search" button, and a div to display the search results. When the user enters a search term and clicks the "Search" button, the search() function is called.

The search() function retrieves the search term from the input field and makes an AJAX request to the server using the XMLHttpRequest object. It sends a GET request to the search.php endpoint (you can replace this with your server-side search script) with the search term as a query parameter. When the server responds, the onload event handler is triggered.

In the event handler, we parse the response (assuming it's in JSON format) and process the search results. If there are results, we create an unordered list (<ul>) and add each result as a list item (<li>) to the list. If there are no results, we display a message indicating that no results were found. If there is an error during the AJAX request, appropriate error messages are displayed on the page.

Remember that in a real-world application, you would need to handle security concerns, input validation, and other error scenarios more robustly. Additionally, consider using modern JavaScript technologies such as fetch or libraries like axios instead of the older XMLHttpRequest.