简体   繁体   中英

Force download of ics file created with php with POST data send from AJAX request collected from user input

I am trying to create a downloadable .ics-file from user input.

The point I am struggling with is the download part.

Code:

jQuery

function sendOnSuccess(){
    var name = jQuery('.member.selected .name').text();
    //day - only the number
    var day = jQuery('.member.selected .calendar .date').text().replace(/\D+/g, '');
    var month = jQuery('.member.selected .calendar .month').text();
    var year = jQuery('.member.selected .calendar .year').text();
    var time = jQuery('.member.selected .slots .selected').text();
    //get everything before :
    var hour = jQuery('.member.selected .slots .selected').text().substring(0, time.indexOf(":"));
    //get everything after :
    var minutes = jQuery('.member.selected .slots .selected').text().split(":").pop();
    var number = jQuery('.member.selected .form input[name="tel"').val();

    jQuery.ajax({
          url: 'download_ics.php',
          type: 'POST',
          data: {
                     name : name,
                     day : day,
                     month : month,
                     year : year,
                     time : time,
                     hour : hour,
                     minutes : minutes,
                     number : number
                 },
          success: function(output){
           // output works
          }
        });
}

download_ics.php

<?php

require_once("ICS.php");

header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename.ics');

$name = $_POST["name"];
$day = $_POST["day"];
$month = $_POST["month"];
$year = $_POST["year"];
$time = $_POST["time"];
$minutes = $_POST["minutes"];
$hour = $_POST["hour"];
$number = $_POST["number"];

$date = strtotime("$year-$month-$day $hour:$minute$timeofday");

$ics = new ICS(array(
  'description' => $name,
  'dtstart' => $date,
  'dtend' => $date . '+ 30 minutes'
));

echo $ics->to_string();

if($number){
  //die(' Success');
  die();
}else{
  die("failed to create");
}

Everything is triggered with this line of html :

<a class="download" href="#" target="_blank" onclick="sendOnSuccess();">Download .ics</a>

So everything works fine - just I cannot figure out how to download the file after it has been created. Everything I get back is just the content of the file.

Inspired by this project: https://github.com/jakebellacera/ics

Could you show us ICS.php? Does is have documentation anywhere?

I would start by changing

header('Content-Disposition: attachment; filename.ics');

to

header('Content-Disposition: attachment; filename="filename.ics"');

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