Am I making a mistake with my Ajax request parameters?

My approach to formulating an Ajax request using prototype involves the following method:

function updateServerStep(stepNumber){
    alert("updating server step to " + stepNumber);
    var params = {stepNumber:stepNumber};
    alert(params.stepNumber);
    var request = new Ajax.Request('UpdateStep', {
          method:'Post',
          parameters:params,
          onSuccess: function(transport){
            alert("Step changed to " + stepNumber);
          },
          onFailure: function(transport){
            alert("Failed!");
          }
    });
}//updateServerStep

I am facing an issue with a servlet that is unable to retrieve the parameters I set in the Ajax method from the request object. The attribute I set is showing as null when I try to access it.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   HttpSession session = request.getSession(true);
   Integer pageNumber = (Integer)request.getAttribute("stepNumber");

   if (pageNumber != null){
        System.out.println("page number was "+ pageNumber.intValue());
        session.setAttribute("secPayStepNum", pageNumber);
    } else {
        System.out.println("page number was null");
        session.setAttribute("secPayStepNum", new Integer(0));
    }   
}

I am unsure if I am instantiating the Ajax request correctly or if there is an error in retrieving the parameters.

EDIT

To clarify the name, I made changes to the JavaScript as shown below:

function updateServerStep(stepNumber){
    alert("updating server step to " + stepNumber);
    var params = {step:stepNumber};
    alert(params["step"]);
    var request = new Ajax.Request('UpdateStep', {
          method:'Post',
          parameters: {'step':"1"},
          onSuccess: function(transport){
            alert("Step changed to " + stepNumber);
          },
          onFailure: function(transport){
            alert("Failed!");
          }
    });
}//updateServerStep

Despite the JavaScript adjustment, the Java side continues to not receive any parameters. I added a loop to print all parameters from request.getAttributeNames(); as shown below:

Enumeration names = request.getAttributeNames();

            System.out.println("Enumerating Attributes:");
            while( names.hasMoreElements()){
                System.out.println("[ELEMENT] "+ names.nextElement().toString());


            }

Unfortunately, the loop does not iterate and no attributes are being sent. I also tried passing a larger array in the params with no success. The Java end does not see any attributes.

I attempted changing the parameters to parameters: "step=1&garbage:'hello world'&foo='bar'" as per the Prototype docs, but it did not result in any attributes server-side. Changing the mode to 'GET' and appending it to the URL also did not send any attributes.

Answer №1

It is advisable to utilize getParameterNames() instead of getAttributeNames().

For further information, refer to:

Review the interface function descriptions to understand the distinctions between the two methods.

Answer №2

Upon a quick review of the prototype documentation, it seems that your request is valid.

I suggest examining the content of the AJAX request directly. You can use tools like Firebug or Charles Proxy to confirm that the POST request contains the necessary data.

REVISION

I overlooked a crucial detail - there is an error in how you are defining the object. You must not reuse an existing symbol as an object property without proper delimitation.

var params = {"stepNumber":stepNumber};

If you fail to do this (let's say stepNumber is 4), then your params object will appear like this

{"4":4}

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

Having the latest Chrome version 98 and matching chromedriver version 98.0.4758.80, coupled with selenium version 3.141.59 - the issue still persists

Launching ChromeDriver 98.0.4758.80 (7f0488e8ba0d8e019187c6325a16c29d9b7f4989-refs/branch-heads/4758@{#972}) on port 12326 Only local connections are permitted. For tips on how to keep ChromeDriver secure, visit https://chromedriver.chromium.org/security ...

Set up a jquery code that ensures a loading effect will only be displayed one time

After clicking on a specific icon, I dynamically add a loading message to the DOM. The issue arises when the user clicks twice, resulting in two instances of the loading message appearing simultaneously. How can I ensure that only one "loading..." message ...

Is there a way to make a text area move along with the mouse cursor?

I have been working on my first website and everything is running smoothly so far. However, I have a new idea that I am struggling to implement. Some of the pages on my site feature a video player with buttons to select different videos. When a viewer hove ...

Execute a function that handles errors

I have a specific element that I would like to display in the event of an error while executing a graphql query (using Apollo's onError): export const ErrorContainer: React.FunctionComponent = () => { console.log('running container') ...

Encountering a java.lang.IllegalArgumentException when attempting to retrieve cookie information using Selenium WebDriver

Recently, I wrote a code snippet to extract data from cookies stored in a text file and display it on a web browser when needed. Here is the code block responsible for storing and writing the cookies to a text file: import java.io.BufferedWriter; import ...

React's constructor being invoked twice

As a newcomer to react, I am in the process of developing a simple web application but encountering an issue. It seems like my Constructor is being called twice when I load a class component. Can anyone provide some assistance? Home.js import React from ...

Express js is failing to deliver static assets

Hello, I'm having an issue with Express Js. It seems like a beginner problem - static files are not being served properly. const express = require('express'); express() .set('view engine','ejs') .use(express.stat ...

Manage customer interactions using Asp.net AJAX

Having an Asp.net AJAX control, I am facing a challenge in handling the onFocus event for multiple textboxes within my control's client control class. I aim to have a single handler for all textboxes, but I am unsure of how to identify which textbox t ...

Eslint in Gulp can't locate my .eslintrc configuration file

My gulp-eslint is unable to locate my .eslintrc file. I've set up a lint task as follows: gulp.task('lint', function () { gulp.src(['src/**/*.js', 'src/**/*.jsx']) .pipe(eslint()) .pipe(eslint.format()); }) The t ...

Numerous demands causing replacements of variable values

I am new to working with nodejs and I have encountered a situation where, upon hitting a specific endpoint, I need to perform two separate post calls. The first post call returns a URL that is required for the second call. Below is a simplified module I cr ...

Error: Unexpected syntax error in JSON parsing after importing PHP file

Encountered an unexpected error: Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data site:stackoverflow.com, which is appearing in the Firefox debug console. On my website, I have a form that triggers this function o ...

Analyzing two arrays and utilizing ng-style to highlight matching entries within the arrays

My list displays words queried from a database, allowing me to click on a word to add it to another list that I can save. This functionality enables me to create multiple word lists. My goal is to visually distinguish the words in my query list that have a ...

Tips for formatting strings to be compatible with JSON.parse

I'm encountering an issue with my node.js application where I am attempting to parse a string using JSON.parse. Here is the code snippet: try{ skills = JSON.parse(user.skills); }catch(e){ console.log(e); } The string stored in user.skill ...

The equivalent of ESM for resolving modules using the `createRequire` function with a specified

In the process of developing a JavaScript instrumentation engine, I am currently focused on traversing a source file's Abstract Syntax Tree (AST) and queuing imported modules for instrumentation in a recursive manner. In order to achieve this, it is c ...

Generating a collection of model objects using Javascript

I want to generate a JavaScript list of my model. I am currently working on an ASP.NET MVC app The model 'testModel' looks like this: public string prop1{ get; set; } public string prop2{ get; set; } public string prop3{ get; set; } ...

Using jQuery to verify the existence of a lengthy object

Is it possible to achieve this functionality using jQuery or other libraries? Dojo has this feature, but what about the others? $.ifObject(foo.bar.baz.qux[0]) if (foo && foo.bar && foo.bar.baz && foo.bar.baz.qux[0]) With an unkno ...

Hover over the image with some padding placed around it to see

I am struggling to figure out how to add padding to my image when hovering over it with Onmouseover. I have tried multiple solutions but none seem to be working. Here is the original code: <img src='/wp-content/uploads/2015/04/img-white.png' ...

Pass data between JavaScript and PHP using the Phaser framework

I am trying to pass a JavaScript variable to PHP and then store it in a database. Despite searching for solutions on Google, I have not been successful. Most suggestions involve using AJAX, but the code doesn't seem to work when I try it. I attempted ...

Move your cursor over the image to activate the effect, then hover over it again to make the effect disappear

Looking to enhance my images with hover effects. Currently, all the images are in grayscale and I'd like to change that so that when you hover over an image, it reverts to full color and remains that way until hovered over again. I've noticed so ...

Can you spot any visible QTips?

My code runs every 5 seconds and may remove or recreate elements that display a QTip to the user. How can I use JQuery to determine if a QTip is currently visible? Thank you. ...