Using variables in a Post request for a JSON object with JavaScript

I am attempting to retrieve an Xmlhttp.response from a website by using the following code snippet:

var apiUrl = "http://somesite/someapicall/correctapiKey";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", apiUrl, false);
xmlHttp.setRequestHeader("Content-Type", "application/json");
var data {
    "username": username,
    "password": hashedPass,
    "someOption": "true",
    "someOtherOption": "true"
}
xmlHttp.send(data);
var response = xmlHttp.responseText;
var parsed = eval('(' + response + ')');

The code works when I manually input the strings for "username" and "password," but fails when using variables. I have checked for errors repeatedly without success.

I must be overlooking something minor, as I have been troubleshooting this issue all afternoon with no luck :(

Can anyone offer guidance or assistance, please?

Edit: The correct values for both the username and password variables are known and provided. The code has been updated to reflect the usage of these variables.

Answer №1

Here's some important information:

 var apiUrl = "http://somesite/someapicall/correctapiKey";

When using an absolute URI like this, be cautious about cross-origin requests and potential issues with the Same Origin Policy. You can also explore ways to work around it.


Take a look at this code snippet:

var data {
    "username": username,
    "password": hashedPass,
    "someOption": "true",
    "someOtherOption": "true"
}

It contains a syntax error. Remember to add an = sign after data.

If "true" is meant to be a boolean value, remove the quotation marks. And always include a semicolon ; after the closing bracket.


You may encounter an issue with this line of code:

xmlHttp.send(data);

Converting data to a string using toString() will result in [Object object]. To send JSON instead, use JSON.stringify(data);


Watch out for this potentially harmful practice:

var parsed = eval('(' + response + ')');

Avoid using eval() as it is considered risky and inefficient. Switch to a safer method by using JSON.parse(response);

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

Are the SystemIndexes in MongoDB influenced by the database contents, or do they remain fixed regardless of changes in the configuration

Currently, we are utilizing full text search functionality on mongo 2.6 by creating indexes using the db.ensureIndex commands. After creating these indexes, we save them as systemIndexes so that developers can import test data with the necessary indexes in ...

What is the process for printing a page in plain text format on a matrix-dot printer?

I've come across many similar questions on SO about this issue, and I've tried various solutions without success. I'm using an Epson LX300+II printer and I want to print pages from my web application in a plain format, like how it would look ...

Locate the nearest index within the array

I'm currently working with an array of "events" where the key assigned to each event corresponds to the Unix Timestamp of that particular event. To illustrate, consider the following array of event objects in JS: var MyEventsArray=[]; MyEventsArray[1 ...

Invalidating the express response object due to a TypeError issue

Currently, I am in the process of writing a test that utilizes sinon and sinon-express-mock to mock an incorrect request. The goal is to then call a validation function within my application and verify that it returns the expected response status code (400 ...

Iterate over the items stored in localStorage and display a particular value when clicked

For my library project, I am trying to create a shopping cart feature. The issue I'm facing is that when I click on a specific book, I cannot add it to another localStorage. This is my html <!--Knjige--> <div class="container grid" id=&ap ...

The jQuery AJAX autocomplete result box is either too cramped or displaying numbers

I'm having some trouble setting up jQuery UI autocomplete with ajax in my project using CI 3.1.5. When I try to implement it, I either get a small result box or just the number of results. Here is my AJAX code snippet: $(".addClient").each(funct ...

PHP API Integration for XBox

Check out this demo link: http://davidwalsh.name/xbox-api I decided to create a php file with the following content.. <?php // Customizations $gamertag = 'RyanFabbro'; $profileUrl = 'http://www.xboxleaders.com/api/profile/'.$gamert ...

What are the steps for making Ajax calls?

I have been working on a Wikipedia viewer for my freecodecamp project. However, I am facing issues with the AJAX request as it keeps failing every time without returning any results. var url, value; $(document).ready(function() { $("button").on("click ...

What is preventing us from receiving JSON as the expected response?

Navigate to the following URL in your web browser: https://hnx.vn/en-gb/cophieu-etfs/chung-khoan-ny.html, then click on page 2. You will notice that the response content is in JSON format. https://i.sstatic.net/0iPSo.png To retrieve the JSON, I created a ...

Is it possible to employ ES6 modules within Node.js 8?

Is it possible to utilize ES6 module syntax with Node.js beginning from version 8? While there are other similar inquiries on this platform, the answers provided may be outdated. I am interested in knowing if the situation has evolved with the latest ve ...

Retrieve the data stored in the `frontmatter` of `.mdx` files with the help of a `.js` script

I am looking to utilize https://github.com/iamvishnusankar/next-sitemap for Sitemap generation. However, when I try using it in the regular way as shown below: next-sitemap.js module.exports = { siteUrl: 'https://example.com', generateRobots ...

Importing Vue and Vuex modules from separate files

Recently, I encountered an uncommon issue. I decided to keep my main.js and store.js files separate in a Vue project. In the store.js file, I imported Vuex, set up a new vuex store, and exported it. However, when importing this file into main.js and settin ...

Unusual happenings detected in Magellan Fixed with Foundation 5

I need help creating a product summary sidebar similar to Apple's. I'm using Magellan but it seems to break the page when the width is below 960 pixels. It might be related to the table, but I'm not sure. Any suggestions or assistance would ...

Encountering the error message "[TypeError]: Unable to access properties of undefined (reading 'prototype')" when utilizing axios post function in next.js

I am encountering an issue while utilizing the next.js app directory and attempting to make a POST request using axios. const submitHandler = async (e) => { e.preventDefault(); try { const {data} = await axios.post('/api/register&ap ...

What is the best way to initiate an event using the onMousewheel function?

I am currently working on a WebGL application where I have a sphere object that utilizes orbit controls for zooming in and out. My goal is to set up an event for the mousewheel so that when I zoom on the WebGL block, the corresponding map location also zo ...

What is the best way to display JSON data in a Listview control?

What is the best way to display JSON data in a list format? Currently, I am able to retrieve JSON data and display it in an alert dialog. The JSON data looks like this: [{"_id":"5449f20d88da65bb79a006e1","name":"name3","phone":"888888","service":"service ...

Toggling event triggers with the second invocation

At this moment, there exists a specific module/view definition in the code: define(['jquery', 'underscore', 'backbone', 'text!templates/product.html'], function($, _, Backbone, productTemplate) { var ProductView = ...

Having trouble retrieving the Enum Value from my response JSON

In my current Flask project for learning purposes, I have created a simple schema for Employees. Here is a snippet of the code (not all column names are included): class GenderChoices(enum.Enum): M = 'M' F = 'F' def __str__ ...

Exporting keys of objects one by one

I am trying to mock the `fs` module in vitest using [memfs](https://github.com/streamich/memfs). To do this, I have created a mock file located at `./__mocks__/fs.ts` where I have set up the mocked volume and fs. However, I am facing an issue with the moc ...

Revamping password security using token-based password reset system

As I work on the password reset feature for my authentication application, I have decided to utilize JWT, node.js, and express. Here's my approach: First, the user enters their email, triggering the generation of a token that is then sent to the user& ...