JSmith
JSmith

Reputation: 4808

Empty file returned with Ajax PHP

I have a JSON string I pass through an Ajax call when triggering a button. The first thing I would like to be able to do and understand would be to pass the variable back in a generated file without saving it to server.

The strange thing that happens here is that the variable value is retrieved by the callback function and is displayed by the alert(data) call, while the POST variable is recognised as empty and the JS script brings me to a blank process-data.php page.

When taking off the empty() condition I still get the variable displayed properly but instead of having a blank page I get a 0 octet file to download.

Could this be a server problem, for info I'm running MAMP?

thanks for your answers.

Here is the HTML code

<button onclick="aCall()" button type="submit" formmethod="post"> DL "x" value as text </button>

Ajax code:

function aCall(){
    $.ajax({
         url: 'process-data.php',
         type: 'POST',
         data: {'value': [{x:250,y:300}]}, //that's an example
         success: function(data){
               alert(data);
               window.location = 'process-data.php';
          }
    });
}

Here is the PHP code:

<?php
   if (!empty($_POST['value'])) //I get a blank page with that condition on and a file if off.
   {
       $filename = 'test.txt';

       header("Content-Description: File Transfer");
       header("Content-Length: ". filesize("$filename").";");
       header("Content-Disposition: attachment; filename=$filename");
       header("Content-Type: application/octet-stream; "); 
       header("Content-Transfer-Encoding: binary");
       header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
       header('Expires: 0');
       header('Pragma: public');

       echo $_POST['value'][0]['x'];
       exit;

    }
?>

in short here is what I get.

HTML -> AJAX -> PHP -> echo myValue
                             |
                             |
       empty file <----------|
       or Blank page         |
                             |
       popup                 |
       showing the <---------'
       variable's 
       value

Upvotes: 0

Views: 350

Answers (1)

Akshay Hegde
Akshay Hegde

Reputation: 16997

Modify like this, no need of json_decode

From

if (!empty(json_decode($_POST['value']))) 

To

if(isset($_POST['value']) && !empty($_POST['value']))

and

From

echo $json[0]->x;

to

echo $_POST['value'][0]['x'];

Upvotes: 1

Related Questions