Here is a small example of code with two buttons: "Select File" and "Download." After downloading the file, the site reloads.

How to implement the button to select and download a file with one click in ajax, so that the site does not restart when loading a file? Thanks in advance for your help.

<div id="block_1" <? if(isset($_POST['send'])){?>style="display:block"<?}?>> <div></div> <div id="block_2"> <?php if (isset($_POST['send'])) { $dir = './image'; $f = scandir($dir); foreach ($f as $file){ if(preg_match('/\.(jpg)/', $file)){ $time_file = date("U", filectime($file)); $time = date('U'); $time_match = $time - $time_file; $delete_time = 1 * 60 * 24; //echo " (".$time_match."сек ) "; if ($time_match > $delete_time) { unlink($file); //echo "Файл удалён"; } //echo "<br />"; } } $new_name = md5(time().rand(0, 500)).'.jpg'; setcookie('url_door', $new_name, time()+3600, '/'); $_COOKIE['url_door'] = $new_name; ini_set('upload_max_filesize', '6M'); //ограничение в 6 мб if ($_SERVER['REQUEST_METHOD'] == "POST" ) { if ($_FILES['inputfile']['error'] == UPLOAD_ERR_OK && ($_FILES['inputfile']['type'] == 'image/jpeg' || $_FILES['inputfile']['type'] == 'image/png' || $_FILES['inputfile']['type'] == 'image/gif')) { $destiation_dir = $_SERVER['DOCUMENT_ROOT'].'/image' . $new_name; // директория для размещения файла if (move_uploaded_file($_FILES['inputfile']['tmp_name'], $destiation_dir)) { //перемещение в желаемую директорию //Файл загружен //оповещаем пользователя об успешной загрузке файла } else { //Файл не загружен } } else { switch ($_FILES['inputfile']['error']) { case UPLOAD_ERR_FORM_SIZE: case UPLOAD_ERR_INI_SIZE: //Файл превышает ограничение brake; case UPLOAD_ERR_NO_FILE: //Файл не выбран break; default: //Что-то пошло не так! } } } } if(isset($_COOKIE['url_door'])){ $cookie_file = $_COOKIE['url_door']; } ?> <? if(isset($_COOKIE['url_door'])){ $cookie_file = $_COOKIE['url_door']; } else { $background_image = "/source/background_img/background_img.jpg"; } ?> <div class="block" style="background: url('<? echo $background_image ?>')0% 100%;background-repeat: no-repeat; margin-top: 16px; margin-left: -20px; width: 890px; height: 454px;"> <p> <input style="display:none;" type="checkbox" checked="1" id="drawSkeleton"></input> <label style="display:none;" for="drawSkeleton">Draw control points.</label> </p> </div> <div id="download_form"> <form method="post" enctype="multipart/form-data" class="form_send_file"> <div class="fileform"> <input style="z-index: -1;" type="file" id="inputfile" name="inputfile" value="Выбрать файл"> <input type="submit" id="input_button" value="Загрузить" name="send"> </div> </form> </div> </div> </div> 

    1 answer 1

    There are already answers to such questions. The correct example is an Ajax request to submit a form using jQuery and JavaScript

    If the image is not transmitted, then send via ajax form data file