Home > other >  Ajax returns data but shows undefined when fetching the param value
Ajax returns data but shows undefined when fetching the param value

Time:09-01

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 { "param1": "value1"}
       console.log(data.param1); returns undefined
    }
});

CodePudding user response:

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);

CodePudding user response:

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

        console.log(d.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"
)
  • Related