How to list a json object to generate a txt file and download that file via ajax request?

3

I have an ajax request that sends a large object. That in the browser console is seen like this:

Object {data: Array[4936], paging: Object} 

The following is the requisition code:

$.ajax({
    type: "POST",
    url: "gerararquivo.php",
    data: response, // é o objeto que foi debugado no console.
    dataType: "json",
    success: function(file){

    }
});

Questions:

1 - How to read the object passed by ajax in PHP. $ _POST [????]

2 - How to scan and list the name of each item data "data.name" via php, ie how would the code to receive the object that was sent via ajax and go through it?

3 - How to make the success of my ajax return me a text file created inside the "generatefiles.php"?

    
asked by anonymous 17.06.2015 / 19:31

3 answers

5

1 - how to read the object

The object sent by Ajax will be available in $ _POST as a multi-dimensional array

2 - how to iterate the object is received

Considering that the following object dados will be sent by POST with jQuery.ajax() , through the data property.

var dados = {
    data: [
        {name: 'foo'}
    ,   {name: 'bar'}
    ,   {name: 'baz'}
    ]
,   paging: {
        current: 1
    ,   total: 10
    }
};

On the server. You should iterate as follows:

<?php
$dados = $_POST['data'];
// array de objetos será recebido como array multidimensional
foreach ($dados as $dado) {
  // acessando propriedade do objeto
  // dados recebidos como array
  $dado['name'];
}
$paging = $_POST['paging'];
// acessando propriedade do objeto
// objeto será recebido como array
$paging['current'];
$paging['total'];

3 - how to download the files

You need to use several relatively new HTML5 API objects, so it may result in errors in outdated / old browsers or IE. These are: Blob , URL and download attribute of <a> .

$.ajax({
  type: 'POST',
  url: 'gerararquivo.php',
  data: dados,
  dataType: 'json',
  success: function(file) {
    var a = document.createElement('a'), blob, url;
    if (typeof a.download === 'undefined') {
      alert('download não suportado pelo navegador');
    } else {
      // criar "arquivo", conteúdo como array e tipo como objeto
      blob = new Blob([file], {type: 'text/plain'});
      // criar URL para arquivo criado
      url = URL.createObjectURL(blob);
      a.href = url;
      // atribuir nome de download do arquivo
      a.download = 'nome_de_download.txt';
      // fazer download
      a.click();
      // revogar URL criada
      URL.revokeObjectURL(url);
    }
  }
});

It is also possible to store the file on the server as suggested in the comments, in which case the concern should be concurrent concurrent requests.

    
17.06.2015 / 21:17
1

1

Taking an example from json_decode

<?php

// neste caso $json seria "response"
$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

?>
    
17.06.2015 / 19:38
1

Simplifying the answer to your questions:

1 - How to read the object passed by ajax in PHP. $ _POST [????]

<?php
     $data = $_POST['data'];
     $paging = $_POST['paging'];
?>

You can also use one to see how the data is coming

2 - How to scan and list the name of each data item "data.name" via php, what would the code look like to receive the object that was sent via ajax and go through it?

This will vary depending on the data type. Ideally, if you post the result of a print_r ($ _ POST) from your PHP file.

For example, date can be an Array of objects, or array of arrays.

In the case of array arrays:

<?php
foreach($data as $d)
{
  echo $d['name'];
  echo $paging->propriedade; //Paging é um objeto... varia de acordo com as propriedades dele
}
?>

In the case of an array of objects:

<?php
    foreach($data as $d)
    {
      echo $d->name;
      echo $paging->propriedade; //Paging é um objeto... varia de acordo com as propriedades dele
    }
?>

3 - How to make the success of my ajax return me a text file created inside the "generatefiles.php"?

There are N ways.

  • You can use the @ Sanction example (You will have problems with some browsers)
  • You can use this reference: link (You will have problems with some browsers)
  • In the php file generate the file and save it to a directory, return the address of that file in the success function, and open a new window pointing to the address where the browser does not matter, the download will happen ...
22.06.2015 / 23:38