Tips for sending a PUT request in Angular with a payload

Currently, I am facing an issue while trying to send a REST request to a web server using the following code:

var getData = function(...) {
    return $http({
      method: "PUT",
      url: getStatistics,
      headers: {
        'loginId': ...,
        'token': ...,
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      data: {"...":"...","...":"...","...":"...","...":"...",
             "...":"....","....":"...",
             "datefrom":"2017-01-01","dateto":"2017-10-20"}
    }).then(function(result){
        var dataString = JSON.stringify(result.data);
        alert(result.data);
        return result.data;
    });
};

The problem arises as I receive a 400 Bad Request error. What steps should I take to resolve this?

The request successfully works on Postman with the specified structure:

https://i.sstatic.net/BBrwF.jpg

https://i.sstatic.net/NbQuO.jpg

Could the issue be related to how I am passing the data object?

I have also implemented the $httpParamSerializerJQLike in the following manner. Is it correct?

app.factory('statistics', function($http,$httpParamSerializerJQLike) {
var getData = function(loginId,token,id,dataInizio,dataFine,periodo,selezione) {
    var data = '{"datefrom":"2017-01-01","dateto":"2017-10-20"}';

    alert(data);
    return $http({
      method: "PUT",
      url: getStatistics,
      headers: {
        'loginId': loginId,
        'token': token,
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      data: { 'data': $httpParamSerializerJQLike(data)}
    }).then(function(result){
        var dataString = JSON.stringify(result.data);
        alert(result.data);
        return result.data;
    });
};

return { getData: getData };
});

Answer №1

when you send an x-www-form-urlencoded body, ensure that it includes a single parameter called data which holds JSON data.

In order to achieve this, you should use:

data: $httpParamSerializerJQLike({data: angular.toJson(data)})

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

Increasing the size of the entire page can be achieved using the three.js dom element

I am currently working on creating a 3D viewer using three.js. My goal is to have the viewer take up the full height of the screen while also leaving space for a side panel. The vertical layout is functioning properly, but once I add the render's dom ...

Problem with jQuery ajax: Sending an array doesn't work

I am attempting to transmit an array of data via AJAX to save it to the database. This is how I construct the array: $( "#saveordering" ).button().click(function( event ) { event.preventDefault(); var data = document.getElementByI ...

Scrolling to the active list item in the navigation bar

Having an unordered list with the id mainul in the navigation bar is causing a problem when the page reloads. The navigation bar always starts at the beginning, but I would like it to automatically scroll to the active li element. This is my HTML code: & ...

What is causing this console to output twice?

My Objective: I aim to utilize Node.js to launch two child processes sequentially at a specific time, displaying their `stdout` as it streams, occasionally alternating between the two processes. The Desired Output: `Proc 1 log # 1` `Proc 1 log # 2` `Pr ...

Why is React's nested routing failing to render properly?

click here for image portrayal I am currently attempting to integrate react router, specifically a nested router. However, when I click the links on the contact page, no results are being displayed. Any assistance would be greatly appreciated. For more in ...

Exploring a utility function for saving object information in a dynamic state

Imagine my state was structured like this: state = { customer: { name: { elementType: "input", elementConfig: { type: "text", placeholder: "Your Name" }, value: "" }, street: { e ...

Using ng-repeat to randomize data displayed from Firebase

Recently, I've been thinking about creating a Firebase database to store quotes. My vision is to structure the data in a way that each quote object looks like this: quotes:{ ObjectId1:{ title: "When there's a will there's a way ...

Unusual method of declaring variables in the world of Eloquent JavaScript

I was diving into the Node.js section of the online version of Eloquent JavaScript (by the way, a fantastic book). The examples all used the following pattern to capture the result of a require() call: const {fs} = require("fs"); However, when I attempte ...

Iterate over the key-value pairs in a loop

How can I iterate through a key-value pair array? This is how I declare mine: products!: {[key: string] : ProductDTO}[]; Here's my loop: for (let product of this.products) { category.products.push((product as ProductDTO).serialize()); } However, ...

using a JSON object as a parameter in a JavaScript function

I am trying to pass specific elements from a JSON object as arguments in a JavaScript function. Here is the script I am using: if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp1=new XMLHttpRequest(); } else {// code ...

Tips for eliminating empty trailing values and Carriage Returns from a JavaScript array

I needed a way to eliminate empty elements and Carriage Returns from the end of an array. Here's an example of what my array looks like: Input arr: ['', 'Apple', '', 'Banana', '', 'Guava', & ...

text shaped into a curve within a container

$().ready(function() { $('#demo1').circleType({fitText:true, radius: 180}); }); $().ready(function() { $('#example').arctext({radius: 250}); }); <script type="text/javascript" src="http://ajax.googleapis.com/ ...

Use React-table to store the value of an accessor in the state while also utilizing a

I am currently working on implementing a checkbox table using react-table. The primary objective is to have checkboxes in the first column, and upon selection of a checkbox, I intend to store the ID defined in the accessor in the state. Despite going thro ...

Integrate javascript into a Wordpress loop while specifying which class to target

Seeking assistance on integrating category icons with animations using snap.svg in a Wordpress page. I have inserted a div containing an svg within the loop that generates the page (index.php). The divs display correctly with the appropriate size of the ...

Unable to access input field value through PHP $_POST array

Having trouble retrieving the value of $_POST['value'] after submitting a form. Implemented a JavaScript function to set a value for an input field. code: function updateValue(pid, value){ // called from a popup window to update the field w ...

Error encountered in Jest (a testing tool for React) - Parse Error: Line 1 contains an invalid import declaration

Currently, I am utilizing node.js version 0.10.x and jest version 0.4.x to conduct tests on react.js. Prior to testing my react components, I was utilizing node.js version 0.12.x. I switched to version 0.10.x using nvm. I proceeded to rebuild all modules ...

Guide to creating a versatile navigation bar using Bootstrap and HTML

I am looking to create a navigation menu that can be easily reused across multiple pages on my bootstrap/html website. Instead of duplicating code, I want to implement a solution for creating a reusable navigation menu in bootstrap/html. How can this be ...

In general, I am seeking ways to streamline my code that is excessively repetitive. More specifically, I am attempting to utilize a single function to access multiple states

Looking for assistance with my new project related to enhancing my skills in react/javascript. I am creating a dice rolling application specifically for tabletop gaming. The aim is to allow users to roll any number of dice of the same size, as well as mult ...

Understanding the reactivity and data management in Vue.js through the use of mixins

I am attempting to create a toggle flag that can switch between boolean values of true and false based on specific conditions. // main.js new Vue({ el: `#app`, render: h => h(App,{ props:{ todoID: this.dataset.id } }) } ...

Removing elements based on the size of the display

I need assistance with a JavaScript issue. I have a table with 2 rows and 5 columns, each column representing a day of the week with a specific class. The goal is to detect the current day based on the browser's width/height and remove all elements in ...