I am trying to code this idea: You have a download button. When you click the button, it should prove if the file exists. When it exists, it should start downloading the file, if not, then there should be an alert.

I know how to prove if the file exists via PHP:

if (file_exists(dirname(__FILE__).'/downloads/rawData.zip')) {
   echo '<script type="text/javascript" language="Javascript">
   location="downloads/rawData.zip"
   </script>'
   ;
} else {
   echo '<script type="text/javascript" language="Javascript"> 
alert("Sorry, no file.") 
</script>';
}

however, the problem is that the button is coded in a html file and should not load a new page as php can't handle a click event.

is there a solution how i can solve the problem?

有帮助吗?

解决方案

What you need is a solution like AJAX. Once the user clicks on the button, you make a request to your PHP script which then return a value based on which you can take the next step.

Here's an example on how to achieve that using the jquery library.

$('#form').submit(function(event) {
    event.preventDefault();
    $.ajax({
       type: 'POST',
       url: 'file-exists.php',
       data: $(this).serialize(),
       dataType: 'json', // could be plain-text as well; depends on your use-case
       success: function (data) {
          console.log(data);
          //do whatever you want based on this data
       }
     });
});

You could also avoid using the library as well, but that would have made it more complicated to explain. You could read more about how to go about doing that, here: http://blog.mgechev.com/2011/07/21/ajax-jquery-beginners/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top