Challenges with xmlHttpRequest in a search autocomplete feature similar to Google's suggestion feature

I am currently working on implementing an autosuggestion search field that functions similarly to Google Suggestion. I am utilizing pure JavaScript/AJAX along with two files: index.php and ajax-submit.php (which is responsible for querying the database). However, at the moment, I am only echoing a text for debugging purposes.

There are a couple of issues that I have encountered:

Problem 1: Initially, the firebug outputs an error stating that xmlhttp is not defined as soon as I start typing in the search input [resolved, see below].

Problem 2: I also want to echo the content of the search input like this:

echo $_GET['search_text']; 

or

if(isset($_GET['search_text'])) {
    echo $search_text = $_GET['search_text'];
}

However, I am encountering the following error: *Undefined index: search_text in ajax-submit.php*

Below is my suggest function call:

<form action="" name="search" id="search">
        <input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>

And here is my suggest() function:

<script type="text/javascript">
    //function does not needs params because is unique to the input search_text
    function suggest() {
    //browser object check
    if(window.xmlHttpRequest) {
    xmlhttp = new xmlHttpRequest();
    }
    else if (window.ActiveXObject) {
    //console.log("error");
    xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
    }
    //when the onreadystatechange event occurs
    xmlhttp.onreadystatechange = function() {

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

        document.getElementByID('results').innerHTML = xmlhttp.responseText;
        }

    }//end onready

    xmlhttp.open('GET', 'ajax-submit.php', true);
    xmlhttp.send();

    }//end suggest

</script>

Additionally, here is the code in my php ajax-submit file:

<?php
echo 'Something';
?>

If anyone could assist me with debugging, it would be greatly appreciated. It seems like it might be a scope issue, but I am uncertain.

Furthermore, how do you typically debug an Ajax request in Firebug?

Thank you

Answer №1

Yes, indeed

fetch()

instead of

Fetch()

For a truly cross-browser compliant fetch object creation, use this approach:

var _fetch_polyfill = [
    'Node-fetch', 
    'Isomorphic-fetch',
    'Whatwg-fetch'
];

var fetch = ( function() {
    var request;
    try {
        request = new fetch();
    } catch( e ) {
        var length = _fetch_polyfill.length;
        while( length-- ) {
            try {
                request = require(_fetch_polyfill[length]);
                break;
            } catch(e2) { }
        }
    } finally {
        return request;
    }
}());

Answer №2

Make sure to utilize:

new XMLHttpRequest

instead of:

new xmlHttpRequest

Answer №3

I revamped the code for better cross-browser compatibility and readability. I also included a function that splits code snippets. Here is the modified code snippet below. Strangely, PHP doesn't seem to read the variable search_text as expected:

    <script type="text/javascript">
    /*note xmlHttp needs to be a global variable. Because it is not it requires that function handleStateChange to pass the xmlHttp
    handleStateChange is written in such a way that is expects xmlHttp to be a global variable.*/
    function startRequest(getURL){
        var xmlHttp = false;
        xmlHttp = createXMLHttpRequest();
        //xmlHttp.onreadystatechange=handleStateChange;
            xmlHttp.onreadystatechange=function(){handleStateChange(xmlHttp);}
        xmlHttp.open("GET", getURL ,true);
        xmlHttp.send();
}

function createXMLHttpRequest() {
        var _msxml_progid = [
        'Microsoft.XMLHTTP', 
        'MSXML2.XMLHTTP.3.0',
        'MSXML3.XMLHTTP',
        'MSXML2.XMLHTTP.6.0'
        ];
        //req is assiqning to xmlhttp through a self invoking function
        var xmlHttp = (function() {
        var req;
        try {
    req = new XMLHttpRequest();
        } catch( e ) {
    var len = _msxml_progid.length;
    while( len-- ) {
        try {
            req = new ActiveXObject(_msxml_progid[len]);
            break;
        } catch(e2) { }
    }
        } finally {
    return req;
        }
        }());

    return xmlHttp;
        }

//handleStateChange is written in such a way that is expects xmlHttp to be a global variable. 
function handleStateChange(xmlHttp){
        if(xmlHttp.readyState == 4){
                if(xmlHttp.status == 200){
                        //alert(xmlHttp.status);
                        //alert(xmlHttp.responseText);
                        document.getElementById("results").innerHTML = xmlHttp.responseText;
                }
        }
}

    function suggest() {

        startRequest("ajax-submit.php?search_text="+document.search.search_text.value");
    }
    </script>

In addition to the JavaScript code, here is the corresponding HTML code:

<body>
        <form action="" name="search" id="search">
        <input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
        </form>
        <div id="results" style="background:yellow"></div>
</body>

Furthermore, here is the content of ajax-submit.php:

<?php
//echo 'Something';//'while typing it displays Something in result div
echo $_GET['search_text'];
?>

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

Learn the steps to modify or remove table information from a database using a webpage

Hey there! I'm currently working on an Ajax jQuery function that displays table data, like in the image provided. I would like to add an option for users to edit and delete the table data, with the changes reflecting in the database. It's worth n ...

Show the current temperature data retrieved from the weather API

I'm trying to figure out what's causing the issue with the temperature not displaying. Can anyone help me identify and fix the error? <script type="text/javascript"> $.ajax({ url: 'https://api.weather.gov/gridpoints/EWX ...

Can we trust the accuracy of Function.prototype.toString for our needs?

Can I trust Function.prototype.toString to provide a valid javascript function string for user-defined functions? Do any popular javascript engines differ in how they represent function objects as strings? I came across this question, but it doesn't ...

No data returned in AJAX response while trying to connect to a RESTful service

After creating a WCF REST service that returns a JSON response like {"Id":10,"Name":"Peter"}, I noticed that when trying to access it using the provided HTML5 code snippet, the status returned is always 0. Can anyone help me figure out what might be caus ...

The text feature for the Google Places API is not displaying properly within the MUI TextField

For address auto-generation, I am currently utilizing the Google Places API. I have a regular input tag in my HTML where users can type their input and see Google Places suggestions in the dropdown - all working perfectly. However, when I switch to using m ...

Tips for customizing the timing of a Bootstrap modal's opening delay?

I have integrated gem "bootstrap-sass", "~> 2.3.0.0", which indicates that I am utilizing Bootstrap 2. Detailed information on the modal can be found here. The code for my custom modal looks like this: #Modal.modal.hide.fade{"aria-hidden" => "true" ...

Personalizing the pop-up window using window.open

When clicking a hyperlink on a page, I need to open multiple pop-up windows. To achieve this, I must use the Window.open function instead of showModalDialog. However, I have noticed that the appearance is not satisfactory when using Window.open. (Essentia ...

Discovering what is impeding the rendering of a webpage

On a particular website, the server rendering happens quickly but there seems to be a delay on the client side which is causing the HTML to be rendered few seconds later. I suspect it could be due to some setTimeout function or similar; are there any tool ...

Is it possible to perform a PHP redirect after the headers have been

I am encountering an issue with a function that needs to redirect the page once a variable is set. The challenge arises from the fact that this function is located at the bottom of the PHP page. As a result, I have already displayed a significant amount ...

Are there any alternatives to PHP for implementing an auto-complete search feature?

I have decided to focus on using HTML, MySQL, JavaScript, and jQuery for my project. Though I understand that learning PHP would be beneficial in the long run, I don't have enough time to master it all within a week. As for the server-side, I will be ...

Guide to refining a JSON array using a pre-established list

I'm in need of assistance figuring out how to accomplish the following task: Below is the code snippet I am working with: public class Data { public string FirstName; public string LastName; public int Age; } var data = new Data { //this objec ...

Import data from a distant file into a node Buffer within the web browser

Currently, I am utilizing browserify to utilize this particular package within the browser. Specifically, I have developed a phonegap application that retrieves .fsc files from the server. The code snippet looks like this: var reader = new FileReader( ...

What are the benefits and drawbacks of combining Jquery UI with AngularJS in web development?

Currently, I am developing a Web application and considering integrating JqueryUI and AngularJS into my ASP.NET MVC project. Is this the best decision for my project? Are there any recommended Databinding libraries that can be used with JQuery UI? Please ...

After refreshing, Angular route using html5Mode leads to a 'Page Not Found' error page

I have created several Angular routes as illustrated in the code snippet below. app.config(function($routeProvider, $locationProvider, $provide) { $routeProvider .when('/', { templateUrl: 'home.html', controll ...

Issue with FlexSlider 2 and thumbnail slider: Previous and Next buttons not functioning for main image

I have encountered an issue while using FlexSlider 2 with the thumbnail slider. The problem is that the main image does not respond as expected. When I try to navigate using the next/prev buttons, it does not slide or fade to the next/prev image. Even cl ...

What is the best way to retrieve the values of a select element from LEVEL 4 within the form submission of LEVEL 3?

To enhance readability, the intricate code has been abstracted. Within our Angular 2 project, we are working with a component called <top-component> (LEVEL 1): <top-component> </top-component> This component includes a template known a ...

Using Browserify to load the npm-module client-side for thepiratebay

I am currently facing an issue with my node.js server file. It successfully loads my site and runs JavaScript, but I encountered a problem when trying to include tpb = require('thepiratebay'); in the server.js file. Although it works fine in the ...

When information is provided, record the values in a separate input field

I'm struggling to come up with an appropriate title... Here's the issue: if a user inputs anything into the "Accompanying Person" field, the "Accompanying Person Price" field will automatically be set to 260€. I have no clue on how to achieve ...

Only one active class is allowed in the Bootstrap Accordion at any given time

I have implemented Bootstrap's accordion on my webpage, consisting of two different sections with unique content. Upon loading the page, the active class defaults to the first element of the first section. However, if I navigate to the "Second" sectio ...

How to Implement Autocomplete Feature in Angular

CSS <div class="dropdown"> <input type="text" formControlName="itemName" (ngModelChange)="filterItems()" class="dropdown-input" (keyup)="onKeyPress($event)" (blur)="toggleDropdown(0)" (focus)="toggleDropdown(1)" placeholder="Search..." [ngCla ...