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

Asked

Viewed 1,746 times

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} 

Follow the request code:

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

    }
});

Doubts:

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

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

3 - How to get the Success of my ajax to return me a text file created inside the "generate.php file." ?

  • Complicated without analyzing the structure of this object, you can post an example of this object received via ajax?

  • You are trying to retrieve the payload sent to you take a look at this question http://stackoverflow.com/questions/9597052/how-to-retrieve-request-payload

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

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

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 files

You need to use several relatively new HTML5 API objects, so it may result in errors in old/outdated or IE browsers. It’s them: Blob, URL and attribute download 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 with concurrent requests.

  • I still don’t understand how the data sent via ajax by php.

  • 1

    @Joaopaulo if the item objeto.data is a array in javascript, in PHP will also be, ie $_POST['data'], then just perform a foreach to travel it: foreach($_POST['data'] as $data) and within the foreach you access the name like this: $data['name']

  • I used JSON.stringfy to pass the object on the ajax date. No $_POST['data'] date is the default name to receive the object or it put only as example?

  • no need to use JSON.stringfy in jQuery AJAX calls. $_POST['data'] is because of the sent JSON object, which has a property data

  • Hi Joao Paulo I believe items 1 of @Sanction is OK. As for item 2, IF the ultimate goal is just to download the file generated by PHP, you can simply redirect to the file using Document.location.href="http://www.site.domain/arquivo.ext" or simply redirect to another page where you can manage downloads. As the final goal is the download, you will not have page redirect, will continue on the same page of the request and the browser will do the normal output. Whereas you just want to download as the ultimate goal

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

?>
  • I don’t know how php receives the data from my ajax request. In your case you put in hand.

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, or how the code would look to receive the object that was sent via ajax and browse it?

This varies according to the type of the data. Ideally, if you post the result of a print_r($_POST) of your PHP file.

For example, data can be an object array, or an 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 object array:

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

3 - How to get the Success of my ajax to return me a text file created inside the "generate.php file." ?

There are N ways.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.