Home Yii2: How to get an array object using Ajax?
Reply: 2

Yii2: How to get an array object using Ajax?

Roby Sottini
1#
Roby Sottini Published in 2018-02-13 20:54:16Z

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.

Syscall
2#
Syscall Reply to 2018-02-14 06:35:18Z

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");
Marais Rossouw
3#
Marais Rossouw Reply to 2018-02-13 20:57:19Z

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]);       
    });
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.310803 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO