简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM