When attempting to invoke a JavaScript function on JSP, there seems to be no

I am currently developing a web application and delving into the intricacies of how Ajax functions within it. I am encountering an issue where nothing occurs when I attempt to select a category, and no errors are being reported.

Within my JSP page:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<link media="all" rel="stylesheet" type="text/css" href="resources/css/all.css" />                  
<script type="text/javascript" src="resources/js/jquery-1.7.2.min.js"/>
<script type="text/javascript">
    var categoryName;
    $(document).ready(function () {
        function doAjaxPost(){
            categoryName = $('#selectCategory').val();
            $.ajax({
                type : "Get",
                url : "loadProducts",
                data : "Category selected =" + categoryName,
                success : function(response) {
                    alert(response);
                },
                error : function(e) {
                    alert('Error: ' + e);
                }
            });
        }
    });
    $("#selectCategory").on("change", doAjaxPost());
</script>


<title>Waiter</title>
</head>
<body>
<h3>Waiter's page </h3>
<h2>
Welcome : ${pageContext.request.userPrincipal.name}
<a href="/logout" class="btn-on">Logout</a>
</h2>
<br>
<c:if test="${!empty productCategoriesList}">
    <spring:message code="label.category" />
    <select id="selectCategory" name="productCategory">
        <option value=" "></option>
        <c:forEach items="${productCategoriesList}" var="productCategory">
            <option value=${productCategory.id}>${productCategory.productType}</option>
        </c:forEach>
    </select>
</c:if>

<div id = "product">
    <spring:message code="label.product" />
    <select>
        <option value = ""></option>
    </select>
</div>

Regarding my Spring Controller:

@RequestMapping(value = "/loadProducts")
public @ResponseBody String loadProducts(@RequestParam("categoryName") 
String categoryName){
    System.out.println(categoryName);
    String str = "Category selected: " + categoryName;
    return str;
}

What steps need to be taken to ensure the proper functionality of this operation?

Answer №1

Ensure that the code

$("#selectCategory").on("change", doAjaxPost());
is placed within the callback function of document.ready()

Answer №2

There are a couple of issues that need to be addressed:

  1. The use of an onxyz-attribute-style handler in the HTML is causing problems because it can only access global functions. Your function doAjaxPost is not global, which is why it's not working as expected.

  2. In addition, your attempt to connect it with jQuery's on also requires doAjaxPost to be global due to its placement in the global scope.

To resolve this issue, you could make doAjaxPost global by moving its declaration outside of the ready callback. However, relying on globals is generally discouraged.

Instead, consider moving your on call inside the ready handler and removing the onchange="doAjaxCall()" from the HTML:

var categoryName;
$(document).ready(function () {
    function doAjaxPost(){
        categoryName = $('#selectCategory').val();
        $.ajax({
            type : "Get",
            url : "loadProducts",
            data : "Category selected =" + categoryName,
            success : function(response) {
                alert(response);
            },
            error : function(e) {
                alert('Error: ' + e);
            }
        });
    }
    $("#selectCategory").on("change", doAjaxPost());    }); // ** Moved**

Also, update the HTML like so:

<select id="selectCategory" name="productCategory">
<!-- No onchange --------------------------------^  -->

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 process of adding asynchronous middleware modules to your express.js application

I'm currently developing an express application that utilizes the node_acl module along with a MongoDB database. I have created a custom module that sets up and configures node_acl asynchronously. This middleware needs to be called as the second piece ...

The message of error is undetermined

Can someone help me with using the errorMessage object from routes in a partial? I have attempted to implement it as shown below: Route:- const express = require("express"); const router = express.Router(); const Character = require("../models/character" ...

Effortlessly retrieving the id attribute from an HTML tag using jQuery

Currently, I am encountering an issue with a code snippet that is designed to extract the value from an HTML tag. While it successfully retrieves a single word like 'desk', it fails when attempting to do so for an ID consisting of two or more wor ...

Can spreading be used for destructuring?

These were the initial props I attempted to pass to a component: const allprops = { mainprops:{mainprops}, // object pageid:{pageId}, // variable setpageid:{setPageId}, // state function makerefresh:{makeRefresh} // state function } <Na ...

Transform the array into an associative array

Below is the array I am working with: print_r($data); When printed in PHP, the result looks like this: $data=Array( [0] => stdClass Object ( [name] => location [value] =>lko ) [1] => stdClass Object ( [n ...

Need a tool for validating forms?

I am currently facing some confusion with the UI Validation plugin that we are using. Within our application, we employ Spring MVC, Jquery & Bootstrap. As we delve into UI development, we have encountered uncertainty in selecting an appropriate Validation ...

Issues with NodeJs Express routes execution

After testing, I found that only the default route "/" is working in my code. Many similar issues involve routers being mounted to paths like "/auth" or "/user". Even when I tested the default router mounted to "/", it still isn't functioning properly ...

Safeguard your database credentials while using AJAX by implementing the best security practices

In the past, I used to keep my database credentials (username and password) in a separate file located outside of the web directory. I would then include this file in my PHP pages to establish connections with the database. However, as I have begun working ...

Prevent scrolling on browser resize event

I am working on a basic script that adds a fixed class to a specific div (.filter-target) when the user scrolls beyond a certain point on the page. However, I am wondering how I can prevent the scroll event from triggering if the user resizes their brows ...

Utilizing Redux Reselect for Comment Filtering

Currently, I am attempting to filter and showcase comments that have a matching 'postID' with the current post id. Utilizing Redux/Reselect, the functionality works well but occasionally an error pops up indicating that post._id is undefined/null ...

Oops! RangeError [MESSAGE_CONTENT_TYPE]: The content of the message must be a string that contains at least one character

Can someone help me troubleshoot my regular send command? I keep encountering an error message even after following suggestions from previous answers. Here is the error: RangeError [MESSAGE_CONTENT_TYPE]: Message content must be a non-empty string. at ...

Can webpack effectively operate in both the frontend and backend environments?

According to the information provided on their website, packaging is defined as: webpack serves as a module bundler with its main purpose being to bundle JavaScript files for usage in a browser. Additionally, it has the ability to transform, bundle, or ...

What is the process for invoking a NodeJS script within a personalized VSCode Extension?

Recently, I created a NodeJS script for one of my projects and now I'm looking to develop a VSCode extension around it. How can I integrate this script as a command within my custom extension? The goal is to have the script packaged along with the e ...

I often find myself feeling unsure when I incorporate conditional logic in JSX within Next.js

Hello, I am currently using Next.js and encountering an issue with using if/else in JSX. When I use if conditions, the classes of elements do not load correctly. Here is my code: <Nav> { login ? ...

Customizing Geonames JSON Ajax Request

Having found the code I needed from a sample website, I am now seeking help to customize it to only display results from the USA. This is the current code snippet: $(function() { function log( message ) { $( "<div>" ).text( message ).pr ...

Showcasing articles in an XML feed according to specific keywords found in the headline

I'm currently working on designing a website for a client and I want to minimize my involvement in its maintenance. I am considering using RSS feeds to automate the process by having content posted on Blogger and then feeding it to the site. However, ...

Manipulate an image by hiding it, altering its contents, and then displaying it

I am seeking the most effective method to accomplish the following task: $("#some-image").fadeOut(); $("#some-image").attr("src", "new-src.png"); $("#some-image").fadeIn(); For timing purposes, the code below is a step closer, but it still needs improvem ...

Angular JS page in its purest form

I have successfully developed a single-page application using AngularJs. However, when I visit the main page of my application hosted on the Heroku server, for a brief moment, all the images and text appear in a raw state at the top left corner of the bro ...

Making changes to two fields simultaneously

Is there a way for me to update the title of an article that is also duplicated in a field named "url" whenever the user enters text into the title field in real-time? Any advice on how I can achieve this? Thank you! ...

What steps can be taken to resolve the issue of the Cannot POST /index.html error?

Here is an example of a calculator app created using HTML and Javascript. Upon running the program with nodemon and accessing localhost:3000, pressing the submit button triggers an error on Google Chrome. [nodemon] starting `node calculator.js` Server sta ...