Alex
Alex

Reputation: 483

Accessing multi JSONs

In the console of the browser I have this: enter image description here

This is returned by this AJAX:

function displayFiles(){
var classElements = document.querySelectorAll("table.folders-list tr.ui-selected td span");
var csrf = $('input[name=_token]').val();
for(var x = 0;x < classElements.length;x++){
    var result;
    result = classElements[x].innerHTML;
    $.ajax({
        async: false,                      
        method: 'POST',
        dataType: 'json',
        url: '../public/getfiles',
        data: { 'folder': result, "_token": csrf  },
        success: function(data) {
        }
    });
}; 
}

I want to access them. Tried console.log(data[0].filename); but got an error. When there is a single JSON I get TypeError: data[0] is undefined, while if there are more than one (just like in the pic) nothing is returned. And this is the PHP function that sends that objects:

public function getFiles() {
    $folder = $_POST['folder'];
    $userid = Auth::id();
    $query = File::orderBy('created_at', 'desc')->where('userid', $userid)->where('folder', $folder)->get();
    // foreach for many result returned by $query
    foreach($query as $result){
        $arr = array();
        $arr['filename'] = $result->filename;
        $arr['id'] = $result->fileid;
        $arr['size'] = $result->conv_filesize;
        echo json_encode($arr);
    }      
}

Upvotes: 2

Views: 43

Answers (1)

fboes
fboes

Reputation: 2239

It seems like you are putting multiple JSON strings just next to each other. This in turn is no valid JSON.

Your output looks something like {"x": 1}{"y": 2}, where it needs to be [{"x": 1},{"y": 2}].

Try outputting all your data in a single call to json_encode():

public function getFiles() {
    $folder = $_POST['folder'];
    $userid = Auth::id();
    $query = File::orderBy('created_at', 'desc')->where('userid', $userid)->where('folder', $folder)->get();
    // foreach for many result returned by $query
    $json = array();
    foreach($query as $result){
        $arr = array();
        $arr['filename'] = $result->filename;
        $arr['id'] = $result->fileid;
        $arr['size'] = $result->conv_filesize;
        $json[] = $arr;
    }    
    echo json_encode($json);
}

You might also try a JSON validator. ;)

Upvotes: 3

Related Questions