3

I have a JSON object that I'm getting as a response to an AJAX call:

{ "Score": 5, "OS": "Windows 7" }

I want to add it to a div but the following does not work, data.OS or data.Score just return as undefined

$.ajax({
     type: "POST",
     url: '/details',
     data: JSON.stringify(IP), 
     contentType: 'application/json;charset=UTF-8',   
     success: function(data) {

        $('#OSdetails').append('<div id="details">Operating System: ' + data.OS + '</div>');

     }
}); 

What am I doing wrong?

5
  • 3
    If you console.log(data), you get exactly Object { "Score": 5, "OS": "Windows 7" }? Commented Apr 18, 2016 at 19:52
  • 1
    What was the requested data type in your Ajax call? If you set it to JSON it will convert automatically. Please show your Ajax call code Commented Apr 18, 2016 at 19:53
  • I updated the code. And yes GG I do. Commented Apr 18, 2016 at 19:56
  • If you use firebug then you can debug the success method and see what paramaters the data paramater has. Commented Apr 18, 2016 at 19:57
  • Can you add the all ajax code? Commented Apr 18, 2016 at 19:58

1 Answer 1

7
$.ajax({
     dataType: 'JSON',         <==== THIS IS MISSING
     type: "POST",
     url: '/details',
     data: JSON.stringify(IP), 
     contentType: 'application/json;charset=UTF-8',   
     success: function(data) {

dataType specifies the expected data type and allows for automated conversion

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

3 Comments

Just a moment, I need to re-setup my server and then I will verify.
Pretty common error. You specified the type of data being send, but not what was expected back.
Worked great, sorry for the slow response. Was having some server issues.

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.