skip to Main Content

I have the below ajax which is returning the data as {"param1": "value1"}. When I try to print the value of param1 by using data.param1, it returns undefined. There is only one value in the data. Am I doing anything wrong here?

    $.ajax({
    'type': "POST",
    'url': "${someresourceURL}",
    // data received is [{"param1": "value1"}]
    'success': function (data) {
       console.log(data);   // returns [Object Object]
       console.log(data.param1); returns undefined
    }
});

3

Answers


  1. seems to work ok, do you need to deserialize the response?

    var foo = {"param1": "value1"};
    console.log(foo);
    console.log(foo.param1);
    var bar = JSON.parse(JSON.stringify(foo))
    console.log(bar)
    console.log(bar.param1);
    Login or Signup to reply.
  2. it must be parsed using JSON before you can use it as JS Dictionary

    Route 1 (Manually doing it)
        $.ajax({
        'type': "POST",
        'url': "${someresourceURL}",
        // data received is [{"param1": "value1"}]
        'success': function (data) {
    
            console.log(typeof data)    // String
    
            d = JSON.parse(data);
            console.log(typeof d)       // Object (array)
            console.log(typeof d[0])    // Object (dict)
    
            console.log(d[0]['param1']);// Returns 'value1'
        }
    });
    
    Route 2 (Signify Return is JSON from the Backend)
    • You’re probably going to have to google yours specifically
    • Ajax will then run JSON.parse() automatically and data will be a dictionary
    PHP
    header('Content-Type: application/json; charset=utf-8');
    
    Python/Django
    return HttpResponse(
        json.dumps(data),
        content_type="application/json"
    )
    
    Login or Signup to reply.
  3. you’re missing dataType: 'json'

    $.ajax( {
        type: 'POST',
        url: '${someresourceURL}',
        dataType: 'json',
        success: function ( data ) {
            console.log( data );
        }
    } );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search