2

When a user clicks download it will successfully create a zip on server with the files, then it should alert the the zips location (variable $zip) from php as a response but instead it is alerting [object Object]. Everything else is working how it should. What am I doing wrong?

JQuery:

$('.download').click(function() { 
window.keys = [];
$('.pad').each(function(i, obj) {
    var key = $(this).attr('key');
        keys.push(key)
});
var jsonString = JSON.stringify(keys);
$.ajax({
      type:'post',
    url:'download.php',
    data: {data : jsonString}, 
        cache: false,
   dataType: 'json',
    success: function(data){

       alert(data);

      }
 });
});

PHP:

<?php


$data = json_decode(stripslashes($_POST['data']));

$numbercode = md5(microtime());
$zip = new ZipArchive();
$zip->open('kits/'.$numbercode.'.zip', ZipArchive::CREATE);

foreach($data as $d) {

$zip->addFile($d);  

}

$zip->close();



echo json_encode($zip);
?>
2
  • 1
    $zip is an object... you are declaring it as new ZipArchive(), therefore it cannot be a string (the file's location) Commented Feb 20, 2017 at 3:40
  • Thanks @jake2389, I now see this! Commented Feb 20, 2017 at 3:41

3 Answers 3

2

The return type is a JavaScript object, which will result in what you see.

First, you should console.log(data), to get the structure. You can also do this by looking at the Network Tab in Chrome.

After you know the structure of data, you can use the value.

For example, then alert(data.location), to alert the actual value.

Sign up to request clarification or add additional context in comments.

Comments

1

remove your dataType from the ajax, it alert [Object Object] because your result becomes json object if you specify dataType: 'json',,

and in php-

// to echo the location of the zipfile
echo 'kits/'.$numbercode.'.zip';

Comments

0

Thanks to @jake2389 I see what I was doing wrong, I basically just had to create a new variable within PHP which I called $link with the data I wanted to send back to AJAX because $zip was defined as a zip archive not a string. Here is what I changed and now it is working.

PHP:

<?php


$data = json_decode(stripslashes($_POST['data']));

$numbercode = md5(microtime());
$zip = new ZipArchive();
$zip->open('kits/'.$numbercode.'.zip', ZipArchive::CREATE);

foreach($data as $d) {

$zip->addFile($d);  

}

$zip->close();

$link = 'kits/'.$numbercode.'.zip';

echo json_encode($link);
?>

1 Comment

I think, there is no need of json_encode in string, if you did change your ajax call, alert problem will not be solved

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.