Download a file and redirect it to another page via ajax

后端 未结 12 2227
盖世英雄少女心
盖世英雄少女心 2021-02-02 09:44

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 wit

相关标签:
12条回答
  • 2021-02-02 10:08

    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

    0 讨论(0)
  • 2021-02-02 10:08

    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.

    0 讨论(0)
  • 2021-02-02 10:08

    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.

    0 讨论(0)
  • 2021-02-02 10:14

    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=/");
    
    0 讨论(0)
  • 2021-02-02 10:16

    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');
    
    0 讨论(0)
  • 2021-02-02 10:20

    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);
    
    0 讨论(0)
提交回复
热议问题