Sending parameters with HTTP GET requests in AngularJS

Currently, I am attempting to pass parameters using the GET method in AngularJS.

$scope.callMethod  = function(url , paramName1, paramName2 ,paramValue1 , paramValue2)
      {

     $http.get('rest/'+url+'?cd='+ (new Date()).getTime(),{params:{paramName1:paramValue1 ,paramName2:paramValue2}}).success(function(data)
                    {
                        console.log("in success block");   
                    }).error(function(data)
                    {
                        console.log("in error block");
                    }
                    );
          }

In this function, I have provided values for all variables, including the paramNames, with the aim of making it reusable. However, when debugging in the browser, I notice that the paramValues are correctly appended but the paramNames are hardcoded. The URL appears as follows:

http://localhost:7001/MyWeb/rest/getProj?cd=1419222398177&paramName1=666560&paramName2=1

I have verified that the URL mapping in my Spring controller is correct. Despite this, I encounter the following error:

 406 (Not Acceptable) 

I am wondering if it is not feasible to use keys as variables in a URL. Thank you in advance for any guidance provided.

Answer №1

The reason behind this behavior is that $http interprets the keys of the params object as query string keys. Therefore, when you provide an object literal inline, such as in your case, the string paramName1 is treated as the actual key.

If you wish to make the value of paramName1 the key, you should structure your params object as follows:

var params = {};
params[paramName1] = paramValue1;
params[paramName2] = paramValue2;

After preparing the params object in this manner, you can proceed to call $http:

$http.get('api/' + endpoint + '?timestamp=' + (new Date()).getTime(), {
    params: params
})

Answer №2

When working with objects, you have the option to use variables as keys. To achieve this, the key variable must be converted into a string before insertion. One way to do this is by following New Dev's suggestion and using brackets to call the .toString method on the variable. Alternatively, you can explicitly utilize JSON.stringify:

var parameters = {};

parameters[JSON.stringify(paramVar1)] = paramVal1;
parameters[JSON.stringify(paramVar2)] = paramVal2;

By employing JSON.stringify, you ensure greater reliability in handling object keys and avoid unexpected results such as [object Object].

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

Executing a CRM javascript button triggers a request to a JSON URL and extracts a specific value

My current task involves creating a button in JavaScript due to system limitations preventing the use of HTML. This button should navigate to a specific URL (REST API to retrieve a JSON file). Furthermore, upon clicking the button, I aim to display an aler ...

The search functionality in the bootstrap-select component is failing when the data token includes only numerical values, such as "4730"

Utilizing to create search options for form selection. The search feature works for all strings except those containing numbers such as "4730". Data is loaded into the select tag from a JSON. Here's an example of the select tag: <div class="col- ...

Troubleshooting problem with JSON object and HTML paragraph formatting

Attempting to incorporate my JSON object value into <p> tags has resulted in an unexpected change in formatting. The output in the console.log appears as shown in this image LINE INTERFACE UNIT,OMNITRON DX-64 LIU Item ...

"Enhancing web interactivity with AJAX requests and dynamic functionality in web

I'm finding it hard to understand the distinction between Rich Internet Applications and AJAX calls. From what I gather, any application that requires client-side execution can be classified as RIA. So, by this definition, should this website be cons ...

Angular's onreadystatechange event is triggered when the state

Hey there, I'm new to Angular and had a question. Is it possible to use the $http service in Angular to trigger a function whenever there is any change in the ready state/status, not just for success or failure? If so, what would be the equivalent ang ...

How can I utilize determinePreferredLanguage in angular-translate to configure based on user language preference?

Within our web application, each user account includes a language setting. This is crucial for ensuring that certain email communications sent from the server side are translated based on the user's language preference. Yet, we are interested in util ...

When node.js v6.11.2 is installed on Windows 7, it does not include the correct npm version

When trying to install node.js v6.11.2 on my Windows 7 computer, I am encountering an issue where it is installing the incorrect version of npm alongside it. Even after downloading the installer directly from node.js' website which claims that 6.11.2 ...

The initial render in a Kanban board seems to be causing issues with the functionality of react-beautiful-dnd

I recently integrated a Kanban board into my Next.js and TypeScript project. While everything seemed to be working fine, I encountered a minor glitch during the initial rendering. Interestingly, when I refreshed the page, the drag and drop functionality st ...

What is the best way to perform a single asynchronous or promise-based fetch request and utilize the retrieved data across multiple functions?

Is there a way to optimize fetching data from an API and use the fetched data in multiple methods within the same service without making redundant requests in the Network? export class MediaService { constructor(private mediaAppApiService: MediaAppApiS ...

Bringing in SCSS using Typescript, React, and Webpack

I am trying to utilize .scss classes by importing them and applying them to the className property of a React component. Here is the structure of my project : root/ ... config/ ... webpack.config.js src/ ... global.d.ts app/ ...

Implementing color with JavaScript by utilizing RGB input boxes

I am currently working on a project where I am attempting to change the color of a text area based on RGB values entered into input boxes. However, I am facing some challenges getting the values to apply correctly. Below is the code snippet I am working wi ...

Notification banner for service maintenance messages with dismiss option available in an Angular application

I need assistance with displaying service messages to users in an Angular application. I want to achieve a similar functionality as showing maintenance-related notifications on Jira board with a dismiss option. The API will provide a list of active message ...

"Learn how to securely redirect to a custom URI scheme with a fail-safe option to display alternative content if not supported

In short: Can a visitor be redirected to a custom URI scheme or shown alternate content if the scheme is not supported? My specific scenario involves developing a mobile app that utilizes a custom URI scheme for users to invite others to actions within th ...

Tools for diagnosing WebGL Three.js issues

Yesterday, I posed a question and now I want to take a different approach while still keeping the previous discussion going. (The initial question was about variable frame rates in Three.js.) Instead of directly addressing that question, I'm curious ...

Uploading files in AngularJS without the need for external plugins

I am in need of code to enable multiple uploads using Angular. The requirements for this task include displaying the name and size of a file before it is uploaded, without the use of any plugins. Additionally, the code needs to be compatible with IE9. Ca ...

The underscore convention for defining members in Typescript allows for clear and concise

Let's talk about a class called Email class Email { private _from: string; private _to: Array<string>; private _subject: string; } When an email object is created, it will look something like this: { _from:'', _to:'&apo ...

Ways to restrict input text to a specific set of values

When using an input text form, I need to ensure that users only insert values ranging from 1 to 10. However, my attempts to utilize a mask for customization have resulted in allowing values higher than 10. How can I restrict the input to only be allowed b ...

What is the best way to ensure blocking on an AJAX call?

When it comes to Ajax, callbacks are used due to its asynchronous nature. I desire my request to the remote URL to wait until a response is received, akin to how Ajax operates, but without the asynchrony. In other words, I seek to create a JAX call. Is t ...

I encountered a console issue that I am struggling with. It is showing the error message "TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'"

When running this code, I encountered an error in the console (TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'). Can someone help me identify where I made a mistake and provide guidance ...

Handling MethodNotAllowedHttpException in IIS, AngularJS, and Laravel: A Comprehensive Guide

Currently, I am diving into the world of AngularJS 1.5.8 + Laravel 5.3.17 + PHP 7 hosted on IIS/Windows 10 by following this helpful tutorial. However, when attempting to send a HTTP request using AngularJS $resource.delete() to Laravel, I keep encounteri ...