0

I am using Yii2 framework for almost a year and now it's the first time I have to use Ajax with an array. I have a this Ajax request:

$.post("/laboratorio/analitos-grupos/analitos-grupos", json)
    .done(function(data) {
        console.log("Data Loaded: " + data);
        console.log("First object: " + data[0]);       
    });

But the console shows:

Data Loaded: [{"id":6,"color":"Blue"},{"id":4,"color":"Brown"},{"id":12,"color":"Red"}]
First object: [

I think it should shows:

Data Loaded: [{"id":6,"color":"Blue"},{"id":4,"color":"Brown"},{"id":12,"color":"Red"}]
First object: {"id":6,"color":"Blue"}

How can I get the first object? Is jQuery the best way to use Ajax in Yii2? I can't find a complete example on Google.

2 Answers 2

3

You're getting a JSON String instead of an array of objects. You could specify that jQuery convert it by specifying json in the 4th argument in jQuery.post() :

$.post("/laboratorio/analitos-grupos/analitos-grupos", json, null, "json")
    .done(function(data) {
        console.log("Data Loaded: ", data);
        console.log("First object: ", data[0]);       
    });

Or, with the callback as success function :

$.post("/laboratorio/analitos-grupos/analitos-grupos", json, function(data) {
    console.log("Data Loaded: ", data);
    console.log("First object: ", data[0]);       
}), "json");
Sign up to request clarification or add additional context in comments.

1 Comment

Since the callback is optional, the null isn't needed.
2

You need to parse the incoming JSON string to a JavaScript Object.

$.post("/laboratorio/analitos-grupos/analitos-grupos", json)
    .done(function(data) {
        console.log("Data Loaded: ", JSON.parse(data));
        console.log("First object: " + JSON.parse(data)[0]);       
    });

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.