-2

I have a form which prompt for a secret key. When the user inserts the key and click submit, it will search for the key in db. If the key is been found, the file relevant to the key has to be downloaded automatically. I have completed till the validation with db using AJAX and php. Now I want the file to be downloaded automatically. How can I do that? (It's better if I can automate the download in php file)

JQUERY

$('#review-submit').on('click',function(){
        var $secret_pin= $('#pin').val();
        jQuery.ajax({
              type : 'post',
              url : ajax_review_plan_object.ajaxurl,
              data : {
                  action : 'loadReviewPlansByAjax',
                  'search': $secret_pin
              },
              contentType: "application/x-www-form-urlencoded; charset=UTF-8",

              success: function(response){
                console.log(response);
                response= response.match(/\d{2}$/);
                if(response==1){
                  $('#empty_pin').fadeIn();
                  $('#invalid_pin').fadeOut();
                  $('#correct_pin').fadeOut();
                  $('#empty_table').fadeOut();
                }else if(response==-1){
                  $('#empty_table').fadeIn();
                  $('#invalid_pin').fadeOut();
                  $('#correct_pin').fadeOut();
                  $('#empty_pin').fadeOut();
                }else if(response==2){
                  $('#correct_pin').fadeIn();
                  $('#invalid_pin').fadeOut();
                  $('#empty_table').fadeOut();
                  $('#empty_pin').fadeOut();
                }else if(response==3){
                  $('#invalid_pin').fadeIn();
                  $('#correct_pin').fadeOut();
                  $('#empty_table').fadeOut();
                  $('#empty_pin').fadeOut();
                }
              }
            });
      });

php

function loadReviewPlansByAjax(){
  $search= $_POST['search'];

  $args = array( 'post_type' => 'reviewplans' );
    $loop = new WP_Query( $args );
    if($loop->have_posts()){
      while ( $loop->have_posts() ) : $loop->the_post();
        // the_title();
        $key = get_field('pin');

        if($search== ''){
          echo 1;
          return;
        } else if($key == $search){
          echo 2;
          return;
        } else{
          echo 3;
        }
      endwhile;
    }else{
      echo -1;
    }
}

   add_action( 'wp_ajax_loadReviewPlansByAjax', 'loadReviewPlansByAjax' );
   add_action( 'wp_ajax_nopriv_loadReviewPlansByAjax', 'loadReviewPlansByAjax' );

  function ajax_coming_soon_enqueues() {
  wp_enqueue_script( 'review-plans-ajax-script', get_stylesheet_directory_uri() . '/framework/assets/js/review-plan-ajax.js', array( 'jquery' ), '1.0.0', true );
  wp_localize_script( 'review-plans-ajax-script', 'ajax_review_plan_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
  }
  add_action( 'wp_enqueue_scripts', 'ajax_coming_soon_enqueues' );
Ramesh
  • 2,297
  • 2
  • 20
  • 42

2 Answers2

0

You have to create a PHP file to validate the key and start download stream. Here's my example using the key on GET method.

if(isset($_GET["key"])){
    $key = $_GET["key"];
    //get key from database

    //Validate the key
    if($key == "key-from-database"){
        if(file_exists("/path/to/file/" . $filename)){
            $o = fopen("/path/to/file/" . $filename, "rb");

            header("Content-Type: "); //Put mime type if you have it. You may left it empty
            header('Content-Disposition: attachment; filename="'. $filename .'"'); //File name is important
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0, max-age=0');
            header("Content-Transfer-Encoding: binary");
            header('Pragma: public');

            echo stream_get_contents($o);
            fclose($o);
        }
    }
}

You use other that fopen() as well.

Mr Hery
  • 829
  • 1
  • 7
  • 25
  • In my case it's a dynamic url. When I applied to your code, I get some console values like boxes and some letters like a encryption. – Ramesh Jul 23 '18 at 10:47
0

your could for example do it like this:

  1. make your ajax call and sent back the result in JSON format with the status = sucess and the link href..
  2. if the status is success -> window.location.replace(link) OR window.open(link,'_blank'); if it should open in a new tab -> this will redirect the user to the file..

as you said you are able to make the ajax call and validate it, I'm not going to post the code on how to do that..

  • Thank you for your answer sir. When I do that I won't be able to get a return value and show/hide the error fields in my form.So I want php to automate the download – Ramesh Jul 23 '18 at 10:49
  • Im not sure if this is possible because if you want to download the file you would have to do it like the answer above, but then you will need to use headers which will cause problems as you commented below.. But does it not work with my second option (opening in a new tab)? if that works you still can do whatever you need to do.. – Christopher Supertramp Jul 23 '18 at 10:54
  • Sounds like I have to change everything.I will try it out sir. Thank you. – Ramesh Jul 23 '18 at 11:27
  • This works awesome.I changed everything.But still I have an issue that I want to download the file automatically. both window.location.replace , window.open didn't work as I expected. Is there any other way that I can try? – Ramesh Jul 23 '18 at 12:52
  • what exactly do you expect? I've tried it with windows.open("https://www.mylinkto.the/downloadfile.zip", "_blank"); and it works perfect.. it shortly opens another tab -> starts the download -> closes the tab and on the main page you can do whatever you like.. – Christopher Supertramp Jul 24 '18 at 05:24
  • I wanted to automate the download.I have done in using jquery. Thank you! – Ramesh Jul 24 '18 at 06:16