Creating a REST API with the POST method using Vanilla JavaScript/AJAX and encountering a 400 error (Bad request) issue

Could you assist me in figuring out how to utilize the POST method in vanilla JavaScript (without jQuery)?

I've been attempting to do so with this code:

var call =
{
  "filterParameters": {
    "id": 18855843,
    "isInStockOnly": false,
    "newsOnly": false,
    "wearType": 0,
    "orderBy": 0,
    "page": 1,
    "params": {
      "tId": 0,
      "v": []
    },
    "producers": [],
    "sendPrices": true,
    "type": "action",
    "typeId": "",
    "branchId": ""
  }
};
var xhr = new XMLHttpRequest();

xhr.open('POST', 'https://www.alza.cz/Services/RestService.svc/v2/products');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
    if (xhr.status === 200) {
        console.log('OK ' + xhr.responseText);
    }
    else if (xhr.status !== 200) {
        console.log('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send(call);

I keep receiving a 400 error (Bad request). I attempted to execute it in jQuery and it worked, but I specifically need it to work in plain JavaScript.

Any thoughts on why it's not working?

Just for comparison, here is the functional jQuery code:

addData({
    "filterParameters": {
        "id": 18855843,
        "isInStockOnly": false,
        "newsOnly": false,
        "wearType": 0,
        "orderBy": 0,
        "page": 1,
        "params": {
            "tId": 0,
            "v": []
        },
        "producers": [],
        "sendPrices": true,
        "type": "action",
        "typeId": "",
        "branchId": ""
    }
}
);

function addData(data){// pass your data in method
     $.ajax({
             type: "POST",
             url: "https://www.alza.cz/Services/RestService.svc/v2/products",
             data: JSON.stringify(data),// now data come in this function
             contentType: "application/json; charset=utf-8",
             crossDomain: true,
             dataType: "json",
             success: function (data, status, jqXHR) {

                 console.log(data);// write success in " "
             },

             error: function (jqXHR, status) {
                 // error handler
                 console.log(jqXHR);
                 alert('fail' + status.code);
             }
          });
    }

Answer №1

Don't forget to specify the content-type header as application/json
Posting JSON data as formdata is incorrect
(also remember to stringify your object)

xhr.setRequestHeader('Content-Type', 'application/json');

Here's an example using the new vanilla JavaScript fetch API:

var result = null

fetch("https://www.alza.cz/Services/RestService.svc/v2/products", {
  method: "POST",
  body: JSON.stringify({
    "filterParameters": {
      "id": 18855843,
      "isInStockOnly": false,
      "newsOnly": false,
      "wearType": 0,
      "orderBy": 0,
      "page": 1,
      "params": {
        "tId": 0,
        "v": []
      },
      "producers": [],
      "sendPrices": true,
      "type": "action",
      "typeId": "",
      "branchId": ""
    }
  }),
  headers: {"content-type": "application/json"},
  //credentials: 'include'
})
.then(function(res) {
  if (res.ok) { // OK if status is in 2xx range
    console.log('OK ' + res.statusText);
  } else {
    console.log('Request failed with status code ' + res.status);
  }

  return res.blob()
})
.then(function(blob) {
  result = blob
  // window.result = blob
})

Answer №2

The reason why the Javascript code is unable to access server data through AJAX is due to the Access-Control-Allow-Origin response. If you do not have control over the server, an alternative option would be to utilize a different server to retrieve the data before redirecting it to your webpage.

Answer №3

Just experimented with the xhr.send() method.

Result obtained:

XMLHttpRequest cannot load https://www.alza.cz/Services/RestService.svc/v2/products. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://www.alza.cz' that is not equal to the supplied origin.

Interestingly, it works fine on a blank tab. What specific URL are you executing this JavaScript from?

Consider running the JS code from a blank tab for successful execution.

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

Utilizing the combineReducers() function yields disparate runtime outcomes compared to using a single reducer

Trying to set up a basic store using a root reducer and initial state. The root reducer is as follows: import Entity from "../api/Entity"; import { UPDATE_GROUPING } from "../constants/action-types"; import IAction from "../interfaces/IAction"; import IS ...

Display Vue component depending on specified attribute

I have a block of code that I am working with: <div> <b-card no-body> <b-tabs pills card vertical no-key-nav v-model="step"> <b-tab title="Subject" v-for="animal in animals" :key="animal&q ...

Exploring the capabilities of Angular's ngResource library and how it

Currently, I am developing a Twitch app and instead of using $http, I opted for ngresource to explore new possibilities. However, I encountered an issue with the offline tab where the users are visible but their logo or username is not displayed. This happ ...

Utilizing React JS to dynamically incorporate form values into objects

I have an array of objects where I need to add a key value State : const [row, setRow] = useState([{ nameofthework: "", schedulerefNo: "", unitprice: "", qty: "", uom: "", gst: "", total: "& ...

The model attribute is returned by Ajax

Let me explain the scenario I am facing. Within my controller, specifically in the viewUserReminders method, I am passing remindersListWrapper to the uReminder.jsp page. @RequestMapping(value = "/user/reminders", method = RequestMethod.GET) public Mod ...

Implementing jQuery Mobile with Rails UJS in order to respect the data-ajax="false" attribute on links that utilize the data-method="delete" functionality

At the moment, I am incorporating jQuery Mobile into my website. However, I have encountered an issue with the logout feature where setting data-ajax=false does not seem to work as expected. This attribute usually prevents the request from being sent via A ...

What are the best techniques for showcasing rich text content in vue.js?

I'm working on a web application and attempting to showcase uploaded rich text content using vue.js. The content is generated by Action Text in the following format. <h1>text</h1><div>sample text<br><action-text-attachment ...

The maximum property in a Mongoose schema does not have any impact or

const mongoose = require("mongoose"); const PostSchema = new mongoose.Schema( { user_id: { type: String, required: true, }, content: { type: String, max: 150, required: true, }, }, { timest ...

What is causing this code to malfunction in AngularJS version 1.2?

Check out this code snippet I wrote using Angular 1.2: http://jsfiddle.net/VmkQy/1/ <div ng-app="app"> Title is: <span my-directive data-title="Test title">{{ title }}</span> </div> angular.module('app', []) .dir ...

I am looking to download a file from a server and showcase it in a browser using React.js. The file will be received as a response from the

**I am looking to retrieve a file from the server by sending the file name through the body and then receiving the requested file from the server.** I have successfully received the file in response from the server, which I tested using Postman. What I a ...

Interacting with external domains through ajax queries

I'm encountering an issue with my javascript code that sends an ajax request, but I'm not receiving any response. Can anyone offer some guidance on how to troubleshoot this problem? Thank you! The URL I am attempting to retrieve is: Here's ...

Displaying PHP content using JavaScript classes

I have a popup feature implemented in JavaScript and all the necessary scripts added to my HTML page. I am attempting to load a PHP page in the popup when the submit button of my form is clicked. The popup is functioning correctly for buttons like the one ...

Tips for retrieving specific database entries using a JavaScript function

I'm currently in the process of developing a web directory that showcases organizations based on the selected county by utilizing an XML database. During testing, I have configured it to only display organization names and counties for now. However, ...

Error: Unable to access attributes of null object (specifically 'disable click')

Currently, I am integrating react-leaflet with nextjs. Within the markers, there are popups containing buttons that open another page upon click. However, I have encountered an error when navigating to the new page: Unhandled Runtime Error TypeError: Canno ...

When attempting to retrieve information from a local database using Django and Ajax by sending parameters to URLs, a 404 error is encountered

Currently, I am striving to retrieve data from my local database utilizing Django and Ajax. I have established a view that enables users to access data while also passing arguments to filter the information. These arguments include start date, end date, an ...

Uncovering the Model within a controller in Ember JS

I am attempting to extract the original model object from a controller for the purpose of persistence (without utilizing ember-data). The straightforward approach would be: controller.get('content'); However, this method is not effective. The i ...

Unlock the App Store instead of iTunes Store using react-native-version-check

I am currently using react-native-version-check to trigger the opening of the app store or play store if an update is available. However, on iOS it redirects to the iTunes store instead of the desired AppStore location. Below is the code in question: ...

After employing a combination of forEach and filter queries in JavaScript to sift through dropdown options, no results are being generated

Hey there fellow developers, I'm currently in the process of developing an app and have reached the stage where I am filtering elements using dropdowns. I am querying a JSON object and comparing it with the selected element in the dropdown at that mom ...

Getting the error message "t is not a function. (In 't(i,c)', 't' is an instance of Object)" while attempting to switch from using createStore to configureStore with React Redux Toolkit

I am attempting to switch from react-redux to its alternative react-redux toolkit but I kept encountering this issue t is not a function. (In 't(i,c)', 't' is an instance of Object) and I am unsure of its meaning. Here is the c ...

Creating interactive dropdown menus with PHP and Catalyst using Jquery

Currently, I am working on incorporating cascading dropdown menus into a catalyst web app. The main goal is to allow users to select a database table from the first dropdown menu and have the columns of that table populate the second dropdown menu. To achi ...