26

I have a simple contact form for download excel file . Main issue happen , When ajax load .I want to download excel file then redirect user to a next page.. Below is my code with dummy data..

Ajax code..

$.ajax({
    type: "POST",
    url: "/site/ajaxexcel.php", 
    data: {'value':'send'},
    cache: false,
    success: function(html){
        location.href = '<?php echo base_url()."/site/welcome.php" ?>';                 
    }
});

And my ajaxexcel.php code is:

<?php 
$content= '<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
    <!--[if gte mso 9]>
    <xml>
        <x:ExcelWorkbook>
            <x:ExcelWorksheets>
                <x:ExcelWorksheet>
                    <x:Name>Sheet 1</x:Name>
                    <x:WorksheetOptions>
                        <x:Print>
                            <x:ValidPrinterInfo/>
                        </x:Print>
                    </x:WorksheetOptions>
                </x:ExcelWorksheet>
            </x:ExcelWorksheets>
        </x:ExcelWorkbook>
    </xml>
    <![endif]-->
</head>

<body><table class="table table-condensed table-striped table-hover table-bordered pull-left" id="myTable"><thead><tr><th>Rakesh</th><th>kumar</th></tr></thead><tbody><tr><th>Rakesh</th><th>Rakesh</th></tr><tr><th>Rakesh</th><th>Rakesh</th></tr><tr><th>Rakesh</th><th>Rakesh</th></tr><tr><th>Rakesh</th><th>Rakesh</th></tr></tbody></table></body></html>';
header('Content-type: application/excel');
header('Content-type: image/jpeg,image/gif,image/png');
header("Content-Disposition: attachment; filename=download.xls");
header("Pragma: ");
header("Cache-Control: ");
echo $content;
?>

I want to just download excel file and then redirect user to a specific location.

Also you can help me with your codeigniter code if you have done it properly..

Kumar Rakesh
  • 2,718
  • 2
  • 18
  • 39
  • I think this link http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax will help you – shafiq.rst Aug 28 '16 at 16:22
  • Thanks for give comment. Actualy , in this way they say, Use external js file . But my ajax code simple and sheduled. So please help me in my code.@user1048123_SOreadytohelp – Kumar Rakesh Aug 29 '16 at 04:23
  • @KumarRakesh Can you add your project folder where we can download. Cz i need more info to help you – Abdulla Nilam Aug 29 '16 at 04:40
  • @KumarRakesh any updates ?? – Abdulla Nilam Aug 29 '16 at 14:07
  • @Spartan .. Sorry for late updates.. As my question.. I have only two files.. I have already fix it by another way.. But thats not my enough answer.. If you can do it . Please try with my code.. – Kumar Rakesh Aug 29 '16 at 16:43

12 Answers12

5

Try below method, hope it will work

  1. open ajaxexcel.php in new window via window.open
  2. it will start downloading, then close it.
  3. As soon as it closes, redirect page.
shyammakwana.me
  • 5,562
  • 2
  • 29
  • 50
  • Thanks For Answer @shaymmakwana.me .. But its not enough and right answer for me. As like you can see my code.. Their are already used header for download file . So can not use header:location code at this file .. – Kumar Rakesh Aug 25 '16 at 09:38
  • I think you misunderstood, you need to write redirection code in your parent window (not in ajaxexcel.php) from where you are opening `ajaxexcel.php`. I suggest try once then get back. – shyammakwana.me Aug 25 '16 at 09:40
  • Ok let me check again. Thanks a lot for quick reply. – Kumar Rakesh Aug 25 '16 at 09:45
  • I try your code in my way.. I think , its not perfectly managable by me.. please can you write code for me. Thanks in advance – Kumar Rakesh Aug 25 '16 at 09:58
4

I think it is very tough to download. Please Use PHP Excel to Create file and download.

Vijju Pundir
  • 163
  • 7
  • Oh ya.. Sound Good.. Thanks I have already try with it. But main issue is redirection. Header action not working after download code. – Kumar Rakesh Aug 25 '16 at 09:17
  • Please use this in PhpExcel $name="file.xlsx"; $objWriter->save('FolderName/'.$name); $path="FolderName/file.xlsx"; header("Location: $path"); – Vijju Pundir Aug 25 '16 at 09:21
  • I got your point . Its not working fine for me ..And also i want to done it with ajax @vijju Pundir – Kumar Rakesh Aug 25 '16 at 09:29
  • I am not agree with this, Using php excel we can create and for downloading the file it's very easy process. – Kapil Yadav Aug 30 '16 at 12:21
4

You can't download file using Ajax request. Any how you have to redirect to particular location which will allow you to download file. Might be you tried with this, but try to download file in separate tab and redirect your page to particular page.

<input id="btnGetResponse" type="button" value="Redirect" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    $("#btnGetResponse").click(function () {
        window.open('/test/excel.php');
        window.location = "http://stackoverflow.com/";
    });
});
</script>

Also from your PHP file (excel.php) remove this line. Otherwise it will download your file as JPG or PNG

header('Content-type: image/jpeg,image/gif,image/png');
Milan Malani
  • 1,818
  • 1
  • 22
  • 34
4

By using https://github.com/johnculviner/jquery.fileDownload js:

$.ajax({
    type: "POST",
    url: "/site/ajaxexcel.php", 
    data: {'value':'send'},
    cache: false,
    success: function(html)
        {
            $.fileDownload("ajaxheader.php",
            {
                successCallback: function (url) {
                    location.href = '<?php echo base_url()."/site/welcome.php" ?>';    
                },
                failCallback: function (responseHtml, url) {
                    alert('error');
                }
            });       
        }
});

And at php side add below line in headers:

header("Set-Cookie: fileDownload=true; path=/");
Hafenkranich
  • 1,696
  • 18
  • 32
Ish
  • 2,085
  • 3
  • 21
  • 38
2

you can use jquery.fileDownload.js for this. you can find an example here . . . http://www.codeasearch.com/working-with-jquery-filedownload-js-plugin.html

Ravikiran kalal
  • 1,050
  • 8
  • 11
  • Their is no full description. And i have used their code But not get a specific result. Please give me a written a code . And also i want to redirect user another page @Ravikiran kalal . – Kumar Rakesh Aug 25 '16 at 09:06
2

Actually for this situation i recommend open file location with blank option and redirect. For this purpose you need create a form structure and submit it to your action.php

Example:

var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "action.php");
form.setAttribute("target", "myView");
// or you can use _blank : form.setAttribute("target", "_blank");

var hiddenField = document.createElement("input"); 
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "message");
hiddenField.setAttribute("value", "val");
form.appendChild(hiddenField);
document.body.appendChild(form);
window.open('', 'myView');
form.submit();
alert("Redirect in 10 second!");
setTimeout(function(){
  location.href = "/home"
}, 10000);
hurricane
  • 6,521
  • 2
  • 34
  • 44
2

By using https://github.com/johnculviner/jquery.fileDownload

Also from your PHP file (excel.php) remove this line. Otherwise it will download your file as JPG or PNG

header('Content-type: image/jpeg,image/gif,image/png');

Vaibhav Walke
  • 445
  • 3
  • 6
2

You can achieve this by creating virtual form and post it.

function autoGenerateAndSubmitForm(method, url, post_data) {
    var element = document.getElementById("virtual_form");
    if(element != null )
    {
        element.parentNode.removeChild(element);
    }
    var form = document.createElement("form");
    form.setAttribute("id", "virtual_form");
    form.setAttribute("style", "display:none;");
    form.setAttribute("target", "_blank"); // This line is very important in your case for redirect in other page and download your file.
    form.method = method;
    form.action = url;   
    for(i in post_data)
    {
         var element=document.createElement("input");
         element.value=post_data[i];
         element.name=i;
         form.appendChild(element); 
    }
    document.body.appendChild(form);
    form.submit();
    form.parentNode.removeChild(form);
}

Call above method where you need it, i assume uyou have call it in click event

$('button').on('click', function(e){
     autoGenerateAndSubmitForm("POST","/site/ajaxexcel.php",{'value':'send'});
     location.href = '<?php echo base_url()."/site/welcome.php" ?>';     
});

Remove below line from your server side code.

header('Content-type: image/jpeg,image/gif,image/png');
Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42
2

In Ajax....Simply you can create an excel file on server ... ajax response will be the path of the excel file...On ajax success open the excel file in new tab (it automatically downloads excel) and at the same time open new tab with new location.

sample code inside ajax success given below

  window.open("path to excel..");
    window.open("new location");

also can use (if needed)

window.location.replace("new location");

Open multiple links in Chrome at once as new tabs

Community
  • 1
  • 1
safin chacko
  • 1,345
  • 1
  • 11
  • 18
2

Method 1 : with jQuery AJAX

Replace your ajax with the following code..

<script>
$.ajax({
    type: "POST",
    url: "/site/ajaxexcel.php", 
    data: {'value':'send'},
    cache: false,
    success: function(html)
    {
        window.open("/site/ajaxexcel.php");
        location.href = '<?php echo base_url()."/site/welcome.php" ?>';                 
    }
});
</script>   

window.open will open the ajaxexcel.php file in separate window and location.href will redirect to given welcome.php file.This is the best method for this.

Method 2 : with jQuery filedownload plugin

Just include jqueryfiledownload script and do something like this:

<a class="download" href="/path/to/file">Download</a>
<script>
$(document).on("click", "a.download", function () {
            $.fileDownload($(this).prop('href'))
                .done(function () { alert('File download a success!'); //success code})
                .fail(function () { alert('File download failed!');//failure code });

            return false; //this is critical to stop the click event which will trigger a normal file download
        });
</script>

Now when you click on anchor your file is downloaded and you can write your success/failure code in done()/fail() functions respectively.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Manjeet Barnala
  • 2,975
  • 1
  • 10
  • 20
  • As like Milan malani answer ,I have already try with this kind of code.. But the main issue is file download open in new window – Kumar Rakesh Aug 30 '16 at 16:55
  • hii @KumarRakesh , I agree that file download will open in new window but the new window will be closed automatically and download dialogue will appear immediately and you will redirected to another page.. – Manjeet Barnala Aug 31 '16 at 13:31
  • One more thing Dear, Its not working in Chrome and Safari. – Kumar Rakesh Sep 01 '16 at 07:42
1

Just use with simple javascript

window.location.replace(###file url###);
1

1) Ajax is not a solution.

2) window.open() popup will be blocked in most browsers even from same domain (at least that was happening in chrome and FF some time ago, when I tried to implement something similar)

Something like this would do the job: (It doesn't check stuff like code returned, so 404 or non-file output will cause a redirect without downloading)

document.getElementById('zzz').onclick = function() {
  ifrm = document.createElement('iframe');
  ifrm.style.display = "none";

  ifrm.src = "https://github.com/SheetJS/test_files/blob/b07031a7bd5a8b86b9baac94267f20cf81c6d5eb/A4X_2013.xls?raw=true"; 
// some random xls file from github (it contains just a single "x" character in cell A-4)
  
  ifrm.onload = function() {
    window.location.href = "https://jquery.com";
  };
  
  document.body.appendChild(ifrm);
  return false;
}
<a href="#" id="zzz">
click me
</a>

P.S.: You will want application/octet-stream Content-type header for some file types (like pdf) to force browser to download file instead of using built-in viewers.

haldagan
  • 911
  • 5
  • 16