facing a problem while parsing see below code
$('#topselector').change(function(){
var url = "<?php echo $this->baseUrl();?>/ajax/get-all";
//var selecter_id = $(this).val();
//alert(selecter_id);
$.ajax({
url: url,
type: "POST",
success: function(data)
{
alert("success");
var obj = $.parseJSON(data);
console.log(obj);
if(obj.meta.code === '200')
{
alert("ok");
$.each(obj.data, function(i,v){
//alert(v.builder_name);
$("#browsers").append("<option value="+v.builder_project_id+">"+v.builder_name+"</option>");
});
}
},
error: function(error){
alert("Error");
}
});
});
getting the output till success after that alerting i.e ok.
my json response is like
{
"meta": {
"code": 200,
"message": "SUCCESS"
},
"data": [
{
"s_no": 1,
"builder_project_id": "389",
"builder_name": "1 389 Sath Build Home",
},
{
"s_no": 348,
"builder_project_id": "4",
"builder_name": "348 4 NA",
}
]
}
I cant understand where i am doing mistake pls suggest in console getting Uncaught SyntaxError: Unexpected token
Your JSON output is invalid.
It is putting unnecessary commas at the last element of the array.
Observe, the removed comma after builder_name
's values.
Corrected JSON:
$json = '{
"meta": {
"code": 200,
"message": "SUCCESS"
},
"data": [
{
"s_no": 1,
"builder_d": "389",
"builder_name": "1 389 Sath Build Home"
},
{
"s_no": 348,
"builder_project_id": "4",
"builder_name": "348 4 NA"
}
]
}';
There is an issue with type check with ===
:
if(obj.meta.code === 200) // <------change to number here
{
alert("ok");
$.each(obj.data, function(i,v){
//alert(v.builder_name);
$("#browsers").append("<option value="+v.builder_project_id+">"+v.builder_name+"</option>");
});
}
another thing i want you to suggest is that you should add:
dataType:"json",
in your ajax which automatically parses the json string. So you need not to use $.parseJSON()
explicitly.