1

I have an array of jsons created in a html file that I would like to pass to the server. When I print out the array in the console just before attempting to POST the results, everything shows up normal. Here is the contents of what I am trying to pass, which is contained in a variable called results:

0: {id: 02934, uName: "Ben", favFood: "ice cream"}
1: {id: 02474, uName: "Sam", favFood: "ice cream"}
2: {id: 01582, uName: "Jamie", favFood: "broccoli"}

But when I go into req.body I find that the array I am trying to pass has undefined variables: enter image description here

I am attempting send the data through an jQuery call seen below:

$("#sendResults").click((event) => {
    console.log(results);
    $.ajax({
         url: '/entertimes',
         type: 'POST',
         data: results
    });                    
});

My goal is to pass the data to the server in a way that is easily manipulatable, meaning that if I typed console.log(req.body.results[0]) it would print out the json contents at that point.


Note: if I update the code to what I have below, i am able to get a string of the json array that I could potentially parse to get the information. However, I want to avoid having to parse it if there is an easier way:

$("#sendResults").click((event) => {
    console.log(results);
    $.ajax({
         url: '/entertimes',
         type: 'POST',
         data: {results: JSON.stringify(results)}
    });                    
});

1 Answer 1

1

When you transmite data from/to server and client side always is in json format. The json is a string. When you send the data, should use JSON.stringify() and JSON.parse() to use the json like an object.

https://en.wikipedia.org/wiki/JSON

Sign up to request clarification or add additional context in comments.

2 Comments

Do you have any advice about how to parse the resulting string from JSON.stringify()? Because of the way the req.body.results object is formatted, I cannot just call JSON.parse(results).
seems like you do not format well the json object. This is the correct format [{"foo": 1}, "bar": "some"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.