Search code examples
phpjqueryjsonjquery-upload-file-plugin

Formatting json response for jQuery upload Plugin


I am using jQuery Upload File plugin and trying to integrate database to it. I need to output the json response correct format like that :

{"files": [
  {
    "id": 1,
    "name": "picture1.jpg"
  },
  {
    "id": 2,
    "name": "picture2.jpg"
  }
]}

What I have at the moment :

[
  {
    "id": 1,
    "name": "picture1.jpg"
  },
    "id": 2,
    "name": "picture2.jpg"
  }
]

My php file looks like that :

$files= array();
$db = new DB;
$query = $db->get_rows("SELECT * FROM `files` ORDER BY `name`");

foreach ($query as $row) {   
  $file = new stdClass();
  $file->id = $row->id;
  $file->name = $row->name;
  array_push($files,$file);
}

header('Content-type: application/json');
echo json_encode($files);

Solution

  • $files= array();
    $db = new DB;
    $query = $db->get_rows("SELECT * FROM `files` ORDER BY `name`");
    
    foreach ($query as $row) {   
      $file = new stdClass();
      $file->id = $row->id;
      $file->name = $row->name;
      array_push($files,$file);
    }
    
    header('Content-type: application/json');
    echo json_encode(array('files' => $files));