<script type="text/javascript">
$(document).ready(function(){
var obj = "";
var param = [{ "name": "id", value: 9}];
$.ajax({
type: 'POST',
url: '2.php',
data: param,
success: function(dataFetch) {
var obj = JSON.parse(dataFetch);
alert(obj[0].name);
},
dataType: 'json',
async:false
});
});
</script>
above is my code. The return result of 2.php is
{"name":"Halford Tee","type":"client","mobile":"1234567","location":"","description":""}
It give me an error
Uncaught SyntaxError: Unexpected end of input
When I remove this part
var obj = JSON.parse(dataFetch);
alert(obj[0].name);
The error is gone. Is there anything wrong with my code?
After looking at valuable guide from fellow programer
My 2.php returns
{"name":"David Tan","type":"leads","mobile":"91234567","location":"","description":""}
I tried the following
$(document).ready(function(){
var obj = "";
var param = [{ "name": "eventId", value: 9}];
$.ajax({
type: 'POST',
url: '2.php',
data: param,
success: function(dataFetch) {
alert(dataFetch[0].name);
},
dataType: 'json',
async:false
});
});
It give me an error
cannot read property 'name' of undefined.
when you use dataType: 'json'
in your ajax then you don't need to use JSON.parse.
your data will automatically be parsed in json format
.so you can directly use it.
use : `alert(dataFetch.name);`// you do not have any array so directly use it.your data is an object not array of object.
note: i think you should use async:false
only when your calling has to complete before the next statement in your function can be called.
After: var obj = JSON.parse(dataFetch);
alert(JSON.stringify(obj));
it might help you to rectify your problem.
(This answer is based on your comment that there might be more than one row.)
I think this is one of those always-1 vs 0-or-more vs 1-or-more problems.
You have to decide, exactly what does 2.php return?
{"name":"David Tan",...}
[{"name":"David Tan",...}, {"name":"Clark Kent",...},...]
{"name":"David Tan",...}{"name":"Clark Kent",...}
In case (1), dataFetch.name
is "David Tan".
In case (2), dataFetch[0].name
is "David Tan".
In case (3), your output is not valid JSON. If you have the ability to change the PHP script, then change the output to Case (2) format <<GOOD SOLUTION. If you must deal with someone else's PHP script, then you need to change your ajax call to dataType: "text"
, then clean it up to make it valid JSON, then parse the JSON client-side. You do not want to omit dataType and have jQuery default to "Intelligent Guess", because results will vary depending on how many rows there are in the output.