Reputation: 3446
I've been trying to figure this out for what seems like forever. My PHP is working fine. As an example, it returns the following if I select "Grove Bow" from my select dropdown:
[{"wtype":"Grove Bow","was":"1.55","wcc":"5","wbdmin":"12","wbdmax":"37"}]
The issue is in parsing the data in the success callback function in my .js file where I have written:
$.post("get.php",
{w:wname},
function(data) {
was = data[1].was;
wcc = data[2].wcc;
wbdmin = data[3].wbdmin;
wbdmax = data[4].wbdmax;
console.log($.parseJSON(data));
}
);
The console returns what I believe to be an empty array:
[Object]
0: Object
length: 1
__proto__: Array[0]
If I remove the $.parseJSON() the console returns the same result that was posted by my get.php file:
[{"wtype":"Grove Bow","was":"1.55","wcc":"5","wbdmin":"12","wbdmax":"37"}]
I need to access these elements of the array as you can see by my attempt to store them as variables (don't worry, I declared them earlier at the top of my .js file).
Pliss halp!
Upvotes: 0
Views: 107
Reputation: 193
The jQuery ajax part looks fine, Try pure Javascript in your callback function:
function(data) {
var json = JSON.parse(data);
console.log(json.wtype); //Grove Bow
console.log(json.was); //1.55
//and so on...
}
Upvotes: 0
Reputation: 61
data
Type: PlainObject or String A plain object or string that is sent to the server with the request.
PlainObject: for the normal operation of a method, you must pass there object like:
{ 'someKey' : 'someVal' , 'sK2' : 'sV2' }
Upvotes: 1
Reputation: 1440
You are trying to access string like it is an object.
Try this
$.post("get.php",
{w:wname},
function(data) {
var json = $.parseJSON(data)[0];
was = json.was;
wcc = json.wcc;
wbdmin = json.wbdmin;
wbdmax = json.wbdmax;
}
);
Upvotes: 0
Reputation: 2631
Console returns you array of objects
and console.log($.parseJSON(data[0]));
will give you your object
Additionaly, you should access your data like this:
var data=$.parseJSON(data);
var myObj=data[0];
var was=myObj.was;
var wcc=myObj.wcc;
//and etc
//or just data[0].was, data[0].wcc
and of course better way, like stated in comment, to use 'json' datatype, instead of calling parseJSON manually
Upvotes: 0