elize
elize

Reputation: 425

Uncaught TypeError: Cannot use 'in' operator in jquery/json

I create a json in php like this:

$details= array();
$ret = array();

for($i=0;$i<3;$i++) { $details["name"] = "name".$i;  $ret[] = $details;}

And then return it to a jquery ajax:

echo json_encode($ret,JSON_UNESCAPED_UNICODE);
die();

In jQuery ajax:

$.ajax({
    url: "index2.php?id=upload",
    type: "POST",
    data:  new FormData($("#form")[0]),
    contentType: false,
    cache: false,
    processData:false,
    returnType:"json",
    success: function(data)
    {
        console.log('names:'+JSON.stringify(data));
        $.each(data, function(i) 
        { 
            console.log('name:'+data[i]['name']);
         }
    },

first console log prints,but second: I get this error:

jquery-2.2.3.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"name":"name1"},{"name":"name2"},{"name":"name3"}]

Also I try

$.each(JSON.parse(data), function(i) 
                { ..}

but I print empty:

name:undefined

Upvotes: 0

Views: 1598

Answers (2)

RiggsFolly
RiggsFolly

Reputation: 94662

When the javascript converts your json string into a javascript data type it will be an array of objects like this

Array
(
    [0] => stdClass Object
        (
            [name] => name0
        )

    [1] => stdClass Object
        (
            [name] => name1
        )

    [2] => stdClass Object
        (
            [name] => name2
        )

)

So your javascript should be

Also returnType:"json" should be dateType:"json" as far as I know there is not such parameter as returnType:

   $.ajax({
        url: "index2.php?id=upload",
        type: "POST",
        data:  new FormData($("#form")[0]),
        contentType: false,
        cache: false,
        processData:false,
        dateType:"json",
        success: function(data)
        {
            console.log('names:'+JSON.stringify(data));
            $.each(data, function(i,v) 
            { 
                console.log('name:'+v.name);
            }
        },

Upvotes: 1

Shahrukh
Shahrukh

Reputation: 102

   $.ajax({
        url: "index2.php?id=upload",
        type: "POST",
        data:  new FormData($("#form")[0]),
        contentType: false,
        cache: false,
        processData:false,
        returnType:"json",
        success: function(data)
        {
            console.log('names:'+JSON.stringify(data));
            $.each(JSON.parse(data), function(i) 
            { 
                console.log('name:'+i['name']);
            }
        },

Upvotes: 1

Related Questions