Jeff
Jeff

Reputation: 1004

AJAX return variable from PHP

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);
?>

Upvotes: 2

Views: 223

Answers (3)

Jeff
Jeff

Reputation: 1004

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);
?>

Upvotes: 0

Veshraj Joshi
Veshraj Joshi

Reputation: 3589

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';

Upvotes: 1

l3utterfly
l3utterfly

Reputation: 2184

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.

Upvotes: 2

Related Questions