Ajax call
$( "#day").datepicker({
onSelect: function(request) {
$.ajax({
type: "POST",
url: '${pageContext. request. contextPath}/url.htm',
data: JSON.stringify({
id: '${someId}'
}),
dataType: 'json',
contentType: "application/json;charset=utf-8",
success: function (response) {
if(response.b === true) {
$("#fruit").val(response.a);
}
}
}).fail(function(xhr, status, error){
console.log('error:' + status + ':' + error + ':' + xhr.responseText);
});
}
});
String response from ajax call is as below
{
"a": "apple",
"b": true
}
I have tried reading it using var json = $.parseJSON(response); and I get exception Uncaught SyntaxError: Unexpected token o
console.log(response); shows data on console as
Object {
"a": "apple",
"b": true
}
I want to fetch value of "a" and "b". How can this be achieved?
Ashley Medway
7,3197 gold badges54 silver badges73 bronze badges
asked Jan 19, 2014 at 10:52
java_dude
4,08810 gold badges41 silver badges62 bronze badges
3 Answers 3
It's already on JSON format. you don't need to parse it anymore.
use it like this.
response.a;
response.b;
answered Jan 19, 2014 at 10:55
Allan Chua
10.3k9 gold badges45 silver badges67 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Please review it I have done some changes :) if any query please ask me
$( "#day").datepicker({
onSelect: function(request) {
$.ajax({
type: "POST",
url: '${pageContext. request. contextPath}/url.htm',
data: JSON.stringify({
id: '${someId}'
}),
dataType: 'json',
success: function (response) {
if(response['b'] === true) {
$("#fruit").val(response['a']);
}
}
}).fail(function(xhr, status, error){
console.log('error:' + status + ':' + error + ':' + xhr.responseText);
});
}
});
answered Jan 19, 2014 at 11:11
Jaskaran singh Rajal
2,3302 gold badges19 silver badges32 bronze badges
1 Comment
java_dude
With JSON datatType, tried both forms:
console.log(response['d']); and console.log(response.d);; Still gets undefinedcheck this:
var ajaxResult = '{"a":"apple","b": true}';
var json= $.parseJSON(ajaxResult );
console.log(json.a);
answered Jan 19, 2014 at 11:03
Shhade Slman
2482 silver badges10 bronze badges
Comments
lang-js
response.aandresponse.bto access value of a and bresponseis not a string it seems. Do atypeof responseand you will see that it is already an object created automatically from the json response.response["a"]andresponse["b"].dataType:'json'