Passing an empty JSON object through Ajax requests

To Whom it May Concern (I am simply attempting to meet the "please add more detail" requirement)

Upon sending data to the server as shown below, the body appears empty.

Server

// Route for POST method
app.post('/pass', function (req, res) {
  console.log("server received a POST from the homepage")
  console.log(req.body)
  res.send('POST request to the homepage')
})

Client

function ajaxJSONFunc(){
      var inputData = document.getElementById('input2').value

      var json = {"data":"abc"};

      $.ajax({
        url: "/pass",
        type: "POST",
        data: json,
        contentType: "application/json",
        // dataType: "json", only use if you need response data to be JSON; an error will occur if uncommented and data is not JSON by default
        success: function(data) {
         console.log("data passed back from server is:" + data)
        },
        error: function(err) {
           console.log("an error occurred")
           console.log(err)
        }
      })
}

It works when passing like this (below), but I would rather send JSON data instead of strings.

  $.ajax({
    url: "/pass",
    type: "POST",
    data: inputData,
    contentType: "application/x-www-form-urlencoded",
    //dataType: "json", only use if response data needs to be JSON; an error occurs if uncommented and data is not JSON by default
    success: function(data) {
     console.log("data passed back from server is:" + data)
    },
    error: function(err) {
       console.log("an error occurred")
       console.log(err)
    }
  })

Answer №1

When you set contentType: "application/json", it means you need to send a json object.

To achieve this, make use of the JSON.stringify() method.

data: JSON.stringify(json)

The JSON.stringify function converts a JavaScript object into JSON text and saves it in a string format.

Answer №2

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script>
$(document).ready(function(){
 var jsonData = "xyz";
$.ajax({
        url: "/sendData",
        type: "POST",
        data: jsonData,
        contentType: "application/json",
        // dataType: "json", uncomment only if response data needs to be JSON, otherwise an error will occur
        success: function(response) {
         console.log("Received data from server:" + response)
        },
        error: function(error) {
           console.log("An error occurred")
           console.log(error)
        }
      });
});
</script>
</head>
<body>
</body>
</html>

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

`Automatic toggling between two inputs with adjustable settings`

There are 2 input fields in my code that only accept positive floats with 2 decimals. Any other characters entered should be automatically removed using the change() function. Whenever the value of one input is changed, the value of the other input should ...

What is the best way to invoke a function in one View Model from within another View Model?

I am looking to divide my DevExtreme Scheduler into two separate view models. One will be responsible for displaying the Scheduler itself, while the other will handle the Popup and button functionality. Despite having everything set up, I am struggling to ...

My mobile website, built using Bootstrap, appears as if it is zoomed

I recently launched a website called dekhbehen.com, where users can download wallpapers and generate memes. One issue I have encountered is that when the site is accessed via smartphone, it appears zoomed out. You can visit the specific URL causing this ...

Toggle the display of dropdown 2 or dropdown 3 depending on the option chosen in dropdown 1

I am struggling with a form that contains 3 dropdowns: <select id="1" required> <option value="">Choose an option</option> <option value="1">Apple</option> <option value="2">Orange ...

I would like to retrieve an array of objects containing state and count information from this data in ReactJS

I have a dataset stored in an array of objects as follows [{name,state},{name,state},{name,state},{name,state},{name,state}]. I am interested in extracting the state data along with the number of people belonging to each state. To achieve this, I would l ...

Unable to classify mapRef.current

I am facing an issue with my react component that contains a leaflet map. TypeScript is warning me about line mapRef.current.setView(coords, 13), stating it is an "unsafe call of an any typed value" import 'leaflet/dist/leaflet.css'; import { Map ...

React and Express are incompatible due to the error message "TypeError: undefined is not a function

I am attempting to display the data from this array on my website using react and express: [{"LocationName":"LIBERTY DOGS","Address":"105 Greenwood Ave N, Seattle WA","Available":"Y"},{"LocationName":"FREEDOM DOGS","Address":"105 Greenwood Ave N, Seattle ...

Discover the secrets of accessing two distinct objects returned by a single REST URL with Backbone

I am working with a REST URL that looks like this: /users/<user_id>/entities This URL returns data containing 2 objects as follows: { "players": { "test_player2": { "_id": "test_player2", "user": "f07590 ...

Ensure to validate the character length prior to saving data using an ajax request

When I try to save data using ajax/jquery, the character length pattern check does not work as expected. The form tag includes: pattern=".{6,}" oninvalid="this.setCustomValidity('Password must be at least 6 characters')" Below is the form and a ...

Creating a dynamic line chart in Primefaces that updates every second in JSF 2

I'm looking to create a dynamic webpage featuring a Primefaces line chart that updates every second. Currently, I retrieve 100 data points from my database in the managed bean. Rather than loading all the data at once onto the line chart, I would lik ...

The window.addEventListener function is failing to work properly on mobile devices

Hey there! I am facing an issue in my JS code. I wrote this code because I want the menu to close when a visitor clicks on another div (not the menu) if it is open. The code seems to be working fine in developer tools on Chrome or Firefox, but it's no ...

Evaluate if the database value matches the current value, then send the result through AJAX

I'm currently working on a web application that uses CodeIgniter to direct users to a jPlayer playlist after they complete a form submission. Recently, my client requested that I update the application to track the amount of time watched for each vid ...

Using a jQuery AJAX request to update the quantity of available items based on user input

Is there a way to use jQuery to capture user input values and product value, then send it to the backend? I need this to trigger an AJAX call that will hit a Java backend. The goal is to provide a product number and quantity value in order to generate th ...

Is it possible to trigger a reflow prior to initiating a lengthy JavaScript operation?

Ready to face the criticism, I understand that this question has been asked many times before, and I am aware that there are likely more efficient ways to achieve what I'm trying to do... In a JavaScript function, I have a process that can take up to ...

The "DELETE" method in ajax is malfunctioning

I encountered an "internal server error (500)" in the console. When checking my NodeJS console, I received a "ReferenceError: request is not defined" message. Below is the code snippet that caused the issue: $(document).ready(function(){ $('.dele ...

What could be the reason for the jQuery animate function not functioning properly?

I am having an issue with this code. I have followed the syntax for animate() but it is not working as expected. <!DOCTYPE html> <html> <head> <style> #testing { background-color: skyblue; Position: absolute; ...

Values in the list of onClick events are currently not defined

I'm having trouble importing a list component into my form and capturing the onClick event to submit the information. However, every time I click on the list, the data shows up as undefined. What could I be doing incorrectly? Here is the code for my ...

Using Javascript to dynamically retrieve accordion content from a dynamically generated ID

I am currently working on developing a more intricate accordion feature. The accordion will consist of 4 buttons (section 0-3) with unique content (lorem ipsum 0-3). Clicking on "section 0" should reveal "lorem ipsum 0", while clicking on "section 1" shoul ...

What is the best method to position images in the same way as seen in the screenshot

Any tips on aligning images shown in the screenshot? Please note that the images will be from the backend. https://i.stack.imgur.com/LnYLM.jpg I experimented with code to position images using top, right, left, and bottom properties, but it becomes cumb ...

Retrieving a file from FormData using ExpressJS

I am new to utilizing ExpressJS for file uploads and sending data through AJAX post as FormData object. I have successfully posted from the front end, but I am having trouble retrieving the data on the server side. Here is the code snippet that I have att ...