What steps can be taken to resolve the issue of Ajax not retrieving any data from

I'm struggling to identify the error in this code. I have created a search bar and implemented AJAX to automatically fetch data.


Here is the HTML file:


<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="bootstrap4/jquery/jquery.js"></script>
    <script>
        function loadproducts()
        {
            var name = document.getElementById("search");
            if(name)
            {
                $.ajax({
                    type: 'post',
                    contentType:false,
                    cache: false,
                    processData:false,
                    data: {
                        products:name,
                    },
                    url: 'loadproducts.php',
                    success: function (response){
                        $('#product_area').html(response);
                    }
                });
            }
            else
            {
                $('#product_area').html("No Product found!");
            }
        }
    </script>
</head>
<body>
<input type="text" name="search" id="search" onkeyup="loadproducts();">
<div id="product_area">

</div>
</body>
</html>

This is my loadproducts.php file:

<?php
include('server/connection.php');

if(isset($_POST['products']))
{

    $name = mysqli_real_escape_string($db,$_POST['products']);

    $show   = "SELECT product_name, sell_price FROM products WHERE product_name LIKE '$name%' ";
    $query  = mysqli_query($db,$show);
    if(mysqli_num_rows($query)>0)
    {
        while($row = mysqli_fetch_array($query))
        {
            echo "<p>".$row['product_name']."</p>";
            echo "<p>".$row['sell_price']."</p>";
        }
    }
}

I even tried adding an alert("called") function in the AJAX success block and the alert does pop up but there is still no output displayed. I also modified

var name = document.getElementById("search");
to
var name = document.getElementById("#search");
without success. Can someone please pinpoint the issue with this code?

Answer №1

Right now, you are interacting with the HTML element itself. To access the value instead, make use of .value:

let username = document.getElementById("search").value;

Alternatively, if you like, you can streamline this by using jQuery:

let username = $("#search").val();

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

Guide to Embedding an Image in a List in HTML

How do I resize an image according to the size specified in CSS, and ensure that it fits within a list of items where each item consists of both an image and a name? Currently, my code only displays the image in its original size. for(var i =0; i< o ...

Guide on presenting an image retrieved from a database with ajax

I am currently developing a straightforward mobile application that utilizes a database to store various types of content, including images. I have implemented ajax requests to retrieve this information and display it within the app. However, I am encounte ...

NodeJS produces identical outcomes for distinct requests

RESOLVED THANKS TO @Patrick Evans I am currently working on a personal web project and could use some assistance. In my website, users are prompted to upload a photo of their face. When the user clicks the "upload" button, the photo is sent with a request ...

The form is failing to redirect to another page

retrieveStudents.js $("#submit").click(function(){ $.ajax({ url: "fetchStudents.php?branchCode=1", datatype:"JSON", success: function(obj){ $("table").append("<form method='POST' action='recordAttendance.php'> ...

Clicking on the Submit button of the post form simply refreshes the page

Every time I try to submit values from an HTML form, the page reloads without any changes. I've double-checked the routes and controller, but everything seems correct. Solution <div class="panel-body"> @if (session('status')) ...

The functionality of Angular 5 reactive form valueChanges is not functioning correctly

I am currently working with a form inside a service: this.settingsForm = this.formBuilder.group({ names: this.formBuilder.array([]), globalIDs: this.formBuilder.array([]), topics: this.formBuilder.array([]), emails: thi ...

Improving Vue Component on Navigation

I am facing an issue with my navbar where I have two versions. Version 1 features a white text color, while Version 2 has black text. The need for two versions arises due to some pages having a white background, hence the requirement for black text. Bot ...

Conceal and reposition divs based on device with Bootstrap's responsive utilities

Utilizing Bootstrap to design a layout that adapts to desktop, tablet, and mobile screens. The desired output is depicted below: In order to achieve this, three divs were created: <div class="row"> <div class="col-md-3">Text</div> & ...

Employing the date time difference when considering different time zones

I came across a helpful link earlier on the topic of calculating time differences in minutes, hours, and days: How to get time difference in minutes in PHP Here is an example I was experimenting with: $date1 = new DateTime('first day of this ...

Executing a sequence of jQuery's $.when().then() functions

I am facing challenges in understanding how to properly sequence my functions, especially in relation to the $.when() method. function y() { defer = $.Deferred(); $.when(defer).then(console.log(defer.state())); } y(); <script src="https://ajax.go ...

The ability to submit a conversation chat is currently

I encountered an issue when attempting to submit a chat, and I received the error message 'handlebar is not define'. I followed the code tutorial provided in this link: https://codepen.io/drehimself/pen/KdXwxR This is the screenshot of the error ...

Is it possible to replace or update the CONSUMER_KEY and CONSUMER_SECRET values in any way?

Currently, I am utilizing Laravel along with the thujohn/twitter package. My goal is to have users provide their own CONSUMER_KEY and CONSUMER_SECRET upon registration. This information will be used for posting tweets, favoriting tweets, etc. The issue is ...

ways to undo modifications made to a value within an input field using jquery or javascript

$(document).ready(function () { //Highlight row when selected. $(function () { $('#Cases tr').click(function () { $('#Cases tr').removeClass('selectedRow'); $(this).addClass(&apos ...

Passing an ID in Next.js without showing it in the URL

I am looking to transfer the product id from the category page to the product page without showing it in the URL Category.js <h2> <Link href={{ pathname: `/product/car/${title}`, query: { id: Item.id, }, }} as={`/p ...

Is it possible to adjust positioning using just CSS?

I'm attempting to arrange these elements as shown in the image below: https://i.stack.imgur.com/tWy1I.png https://jsfiddle.net/ut1mgcLb/ HTML <div class="object1"> <div class="snax-voting-container-body"> ...

What could be the reason for the handleOpen and handleClose functions not functioning as expected?

I am facing an issue with my React component, FlightAuto, which contains a dropdown menu. The functionality I'm trying to achieve is for the dropdown menu to open when the user focuses on an input field and close when they click outside the menu. Howe ...

Utilizing PHP for loading a fresh webpage within a specific div element of an existing page through AJAX

<!doctype html> <head> <title>Homepage</title> <style> #header{background-color:#09C; width:100%; height:100px;} #logoandsearch{background-color:#603; width:400px; height:40px; float:left; margin-top:30px; margin-left:1 ...

What is the best way to avoid using ng-repeat for the last item being shown?

I currently have an ng-repeat loop that is dependent on an ng-if condition. Here is the specific code block: <div class="fav-prod-customised> <p ng-repeat="ingredient in product.options" ng-if="ingredient.default_quantity == 0 & ...

Utilizing Multiple Select Options and CSS Float Styling in Mozilla Firefox

I have been attempting to customize the CSS of a multiple select element. While I am satisfied with how it looks on Chrome, I am facing issues getting it to work correctly on Mozilla Firefox. $('option').mousedown(function(e) { ...

Exploring the synergies of Remark and Rehype plugins alongside MDX in Next.js powered by @next/mdx

I’ve been experimenting with Github Flavored Markdown using @next/mdx, but I’m struggling to understand how to use plugins alongside the code. Here’s a breakdown of what I’ve attempted so far: (I’m following the instructions from the Next.js Doc ...