0

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!

1
  • 1
    The answer posted is correct, and beyond that, you can also use }, 'json'); to have the data returned automatically parsed as json. Commented Mar 23, 2013 at 1:01

4 Answers 4

1

Jquery.post() :

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' }
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

0

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...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.