0

I am using an AJAX POST to send a JSON object from the client side my server. However, I'm a little confused as to how to access the object once it gets there.

Here's my POST from the client side:

var data = JSON.stringify({
       'app': 'reviews',
       'name': '',
       'review': '',
       'response': '',
       'rating': rating,
       'url': url,
       'date': date
     });
     console.log(data);
     $.ajax({
           type: "POST",
           url: "https://stormy-plateau-94715.herokuapp.com/",
           data: JSON.stringify(data),
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           success: function(data) {
             alert(data['success']);
           },
           failure: function(errMsg) {
             alert(errMsg);
           }
       });

This works just fine. On my server, I print the body of the request and it looks fine:

"{\"app\":\"reviews\",\"name\":\"\",\"review\":\"\",\"response\":\"\",\"rating\":4.5,\"url\":\"test.com\",\"date\":\"7/5/2016\"}"

Then I call JSON.parse on it, and everything still works as I expected, here is the result:

{"app":"reviews","name":"","review":"","response":"","rating":4.5,"url":"test.com","date":"7/5/2016"}

This is saved in a variable called post. However, when I try to access post.app or post['app'], I get an undefined. Can anybody let me know where I'm going wrong?

3
  • Use $_POST['app'] on server side Commented Jul 5, 2016 at 6:07
  • 2
    why are you using JSON.stringify twice? Commented Jul 5, 2016 at 6:11
  • Poonam and FDavidov were right, I used stringify twice. I used console.log(post) to print the post variable. Commented Jul 5, 2016 at 6:24

2 Answers 2

2

This very same issue happened to me when I mistakenly used JSON.stringify on an object that was already a string, which it looks is exactly what you are doing.

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

Comments

1

change

var data = JSON.stringify({
   'app': 'reviews',
   'name': '',
   'review': '',
   'response': '',
   'rating': rating,
   'url': url,
   'date': date
 });

to

var data = {
   'app': 'reviews',
   'name': '',
   'review': '',
   'response': '',
   'rating': rating,
   'url': url,
   'date': date
 };

Comments

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.