JavaScript function encountering a reference error while using AJAX

Currently, I am utilizing AJAX to perform a keyword search on a MySQL database. The issue arises when the results are displayed and I attempt to click on an option, as it generates a reference error in Firebug. Here is the code snippet:

<html>
<body>
    <style>
        #displayDiv {
            background-color: #ffeeaa;
            width: 200;
        }
    </style>
    <script type="text/javascript">
        function handleClick(selectedItem) {
            var selected = selectedItem;
            alert(selected);
        }
    </script>
    <script type="text/javascript">
        function ajaxFunction(searchTerm) {
            var httpxml;
            try {
                // Firefox, Opera 8.0+, Safari
                httpxml = new XMLHttpRequest();
            } catch (e) {
                // Internet Explorer
                try {
                    httpxml = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                    try {
                        httpxml = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e) {
                        alert("Your browser does not support AJAX!");
                        return false;
                    }
                }
            }

            function handleState() {
                if (httpxml.readyState == 4) {
                    document.getElementById("displayDiv").innerHTML = httpxml.responseText;
                }
            }
            var url = "search.php";
            url = url + "?txt=" + searchTerm;
            url = url + "&sid=" + Math.random();
            httpxml.onreadystatechange = handleState;
            httpxml.open("GET", url, true);
            httpxml.send(null);
        }
    </script>
    </head>
    
    <body>
        <form name="myForm">
            <input type="text" onkeyup="ajaxFunction(this.value);" name="username"/>
            <div id="displayDiv"></div>
        </form>
    </body>

Below is the content of the search.php file:

<?php
include ("dbinfo.php");
$keyword = $_GET['txt'];
$message = "";

if (strlen($keyword) > 0 and strlen($keyword) < 20) {
    $query = mysql_query("select RubroId, RubroDisp from rubros where KeyWords like '$keyword%'");

    while ($row = mysql_fetch_array($query)) {
        $value = $row[RubroDisp];
        $encodedValue = str_replace(" ", "_", $valor);
        echo "<a href='#' onclick='handleClick($encodedValue);'>$value</a><br />";
    }
}
?>

You can view the functioning page by visiting this URL.

Could you please provide guidance on resolving this issue or point out any mistakes I may have made?

Thank you.

Answer №1

Using aca($encodedValue); in your code will result in JavaScript code that invokes a function with an undefined variable as the argument. If you intend to pass a string, make sure to enclose it in quotes.

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

File handling in Angular 2 using Typescript involves understanding the fundamental syntax for managing files

Would someone be able to explain the fundamental syntax for reading and writing text files, also known as file handling in TypeScript? If there is a corresponding link that anyone could provide, it would be greatly appreciated. ...

exchanging a library for a different one

I'm faced with a relatively simple task here, but as I am just beginning to delve into object-oriented programming, it is proving to be quite perplexing for me. Currently, I am using the lon_lat_to_cartesian function from the following source: functi ...

Utilizing GTM to Implement Dynamic Content Deployment

Can you provide guidance on the entire process from creating a Custom HTML Tag in GTM to executing JavaScript for firing dynamic HTML code, such as displaying a div with text or image based on a specific rule like the referral or cookie variable? For exam ...

Variations in the module pattern in JavaScript

Can someone help me understand the differences in these methods of creating a javascript "module"? I'm just looking for some clarification. A) var foo = function() { var bar = function() { console.log('test'); }; retur ...

Incorporate React JS seamlessly into your current webpage

As I delve into learning React and considering migrating existing applications to React, my goal is to incorporate a React component within an established page that already contains its own HTML and JavaScript - similar to how KnockoutJS's `applyBindi ...

Dealing with a syntax error in JavaScript (Codecademy)

I have been working my way through the JavaScript course on Codeacademy and for the most part, I've been able to figure things out on my own. However, I've hit a roadblock with my code and can't seem to get it right. Here is the code I&apos ...

Unable to interact with array members within a Prisma model that involves a relational table. Utilizing next.js, Prisma, and TypeScript for development

I have set up two tables with a relationship: Categories and Articles. Prisma has built the relationship, and everything seems to be in order. Here is the structure of the Category table: model Category { id Int @id @default(autoincrement()) ...

I require assistance in configuring the timing for an animation using Jquery

How can I adjust the timing (delay between two words) for this animation? If you need help, you can check out this link for guidance. Feel free to share your suggestions! ...

Utilizing conditional styling in React: the ability to add or attach CSS classes based on

Is there a more efficient way to implement conditional formatting for this scenario? const PaginationStorePageLink = ({ store, pageNum }) => (observer(({ PaginationStore }) => { const className = this.props.store.currentPage === this.props.pageNum ...

What is the best approach to breaking down attributes upon import according to the theme?

Hey there! Here's the thing - I have this file called <code>colors.ts:</p> export const black = '#0C0C0C'; export const blue = '#22618E'; Whenever I need to use a color, I import it like so: import {black} from 'S ...

Change the width of the :after pseudo-element in CSS using jQuery

I've been attempting to dynamically adjust the width of an element using :after, but for some reason, my changes are not being applied. Can someone offer assistance with this issue? $(function(){ var a=20; $(".progress:after").width(a+"%"); // Desp ...

With each consecutive trigger, the AJAX form in Rails 4.2 submits to the server at an increasing rate

When I select a company from the dropdown list in a form, it triggers an update in another dropdown list for addresses through an AJAX request. The address options are successfully updated each time. However, I noticed that when I switch between companies ...

The issue arises when the d3 startAngle and endAngle values are set to NaN, resulting in an

I am working with a dataset that includes the following information: { current: 5 expected: 8 gap: -3 id: 3924 name: "Forhandlingsevne" progress: "0" type: 2 } Now, I have implemented the ...

Add animation to the jQuery ajax response

Is there a way to animate jQuery when receiving new input via ajax without refreshing the page? The getAVG.php file returns the average of a database field. Check out this example page Here is the code snippet: (function(){ var avg; $.ajax({ ...

Troubleshooting pathing issues with Three.js and the useGLTF hook

Currently, I am working on a basic project using next.js and trying to explore three.js. However, I have encountered a simple yet challenging issue that I can't seem to solve. In the screenshot attached, you can see my project structure. Within Sculp ...

Ensure the configuration is stored in a safe location where files cannot be accessed through external links

Currently, I am attempting to utilize a configuration file for both a database and rating script. However, the dilemma lies in the fact that the config file is located in this directory: website.com/include/config.php also known as websitename/include/co ...

What is the best way to eliminate the unnecessary space that appears by default in the Ajax control toolkit tab panel control

When using the Ajax Control Toolkit tab panel, you may notice that there is automatic spacing added around all four corners of the body. For instance, when viewing the TabPanel on the page http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/Tabs/Tabs.aspx ...

Display the value on the screen based on the specified condition

Extracting the "address" value from the backend yields an uppercase result. To format it with only the first letters capitalized, I implemented a solution. However, an issue arises when the "address" value is missing. const capitalizeFirstLetter = (string) ...

Experiencing some unusual shadows in my Three.js project while attempting to add a simple shadow effect to a cube or group of cubes

Trying my hand at implementing shadows in Three.js, even though I am fairly new to JavaScript. My attempts to create a cube with a proper shadow have yielded partial results, as only a portion of the mesh seems to be casting the shadow. https://i.sstatic. ...

The Benefits of Semantic Class Names compared to Microdata

As I strive to use semantic class names, my exploration of microdata and SEO raises a question: Is it necessary to use both? Compare these two HTML snippets representing an event: Using CSS classes: <div class="event" itemscope itemtype="http://schema ...