Вывод файла при клике на определенную запись в название

Рейтинг: 0Ответов: 0Опубликовано: 17.05.2023

Требуется - в название вводится какой либо текст под полем появляются варианты , при клике на какой- либо в других полях ввода появляются информация и файл должен прикреплятся и выбираться согласно названия. Работает лишь подстановка в поля ввода , кроме файла. Как это реализовать?

entry.php

    <script>
        $(document).ready(function() {
            $('#title').on('input', function() {
                var search = $(this).val();
                if (search != '') {
                    $.ajax({
                        url: '/vendor/search.php',
                        method: 'POST',
                        data: {
                            search: search
                        },
                        success: function(response) {
                            $('#title_list').html(response);
                            $('#title_list').fadeIn();
                        }
                    });
                } else {
                    $('#title_list').fadeOut();
                }
            });
            $(document).on('click', '.title_item', function() {
                var title = $(this).text();
                $('#title').val(title);
                $('#title_list').fadeOut();
                var file = $(this).data('file');
                var author = $(this).data('author');
                var publicationtype = $(this).data('publicationtype');
                var place = $(this).data('place');
                var year = $(this).data('year');
                var publisher = $(this).data('publisher');
                var compedit = $(this).data('compedit');
                var countpages = $(this).data('countpages');
                var archive = $(this).data('archive');
                var BBK = $(this).data('BBK');
                var inventnumber = $(this).data('inventnumber');
                var numbinstances = $(this).data('numbinstances');
                var lasttaker = $(this).data('lasttaker');
                if (author) {
                    $('input[name="author"]').val(author);
                }
                if (publicationtype) {
                    $('select[name="publicationtype"]').val(publicationtype);
                }
                if (place) {
                    $('input[name="place"]').val(place);
                }
                if (file) {
                    $.ajax({
                        url: '/vendor/get_image.php',
                        method: 'POST',
                        data: {
                            file: file
                        },
                        dataType: 'json',
                        success: function(response) {
                            // создаем элемент a для скачивания файла
                            var downloadLink = document.createElement('a');
                            downloadLink.href = 'data:image/png;base64,' + response.data;
                            downloadLink.download = file;
                            downloadLink.style.display = 'none';
                            document.body.appendChild(downloadLink);

                            // эмулируем клик на элементе a
                            downloadLink.click();

                            // удаляем элемент a
                            document.body.removeChild(downloadLink);
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                            // обработка ошибок
                        }
                    });
                } else {
                    $('#preview_file').attr('data-file', "");
                    $('#preview_file').attr('src', "");
                }
                if (year) {
                    $('input[name="year"]').val(year);
                }
                if (publisher) {
                    $('input[name="publisher"]').val(publisher);
                }
                if (compedit) {
                    $('input[name="compedit"]').val(compedit);
                }
                if (countpages) {
                    $('input[name="countpages"]').val(countpages);
                }
                if (archive) {
                    $('input[name="archive"]').val(archive);
                }
                if (BBK) {
                    $('input[name="BBK"]').val(BBK);
                }
                if (inventnumber) {
                    $('input[name="inventnumber"]').val(inventnumber);
                }
                if (numbinstances) {
                    $('input[name="numbinstances"]').val(numbinstances);
                }
                if (lasttaker) {
                    $('input[name="lasttaker"]').val(lasttaker);
                }

            });
        });
    </script>
     <div class="parent">
                <td>
                <input type="hidden" name="selected_file" id="selected_file">
                    <img id="preview" onclick="openModal(this);">
                    </br>
                    <input type="file" name="file" onchange="previewImage(this)">
                </td>
            </div>
            <br>
            <div class="label">
                <label>Название:</label>
                <td>
                    <input type="text" name="title" id="title">
                    <div id="title_list" style="text-align: center;"></div>
                </td>
            </div>
            <br>
            <div class="label">
                <label>Тип издания:</label>
                <select name="publicationtype">
                    <option value=""></option>
                    <option value="Однотомное издание">Однотомное издание</option>
                    <option value="Многотомное издание">Многотомное издание</option>
                    <option value="Собрание сочинений">Собрание сочинений</option>
                    <option value="Периодическое издание">Периодическое издание</option>
                </select>
            </div>
            <br>
            <div class="label">
                <label>Авторы и составители:</label>
                <td>
                    <input type="text" name="author">
                </td>
            </div>
            <br>
            <div class="label">
                <label>Под редакцией:</label>
                <td>
                    <input type="text" name="compedit">
                </td>
            </div>
            <br>
            <div class="label">
                <label>Место:</label>
                <td>
                    <input type="text" name="place">
                </td>
            </div>
            <br>
            <div class="label">
                <label>Год:</label>
                <td>
                    <input type="text" name="year">
                </td>
            </div>
            <br>
            <div class="label">
                <label>Издательство:</label>
                <td>
                    <input type="text" name="publisher">
                </td>
            </div>
            <br>
            <div class="label">
                <label>Количество страниц:</label>
                <td>
                    <input type="text" name="countpages">
                </td>
            </div>
            <br>
            <div class="label">
                <label>Архив:</label>
                <td>
                    <input type="text" name="archive">
                </td>
            </div>
            <br>
            <div class="label">
                <label>ББК:</label>
                <td>
                    <input type="text" name="BBK">
                </td>
            </div>
            <br>
            <div class="label">
                <label>Инвентарный №:</label>
                <td>
                    <input type="text" name="inventnumber">
                </td>
            </div>
            <br>
            <div class="label">
                <label>Количество экземпляров:</label>
                <td>
                    <input type="text" name="numbinstances">
                </td>
            </div>
            <br>
            <div class="label">
                <label>Кому выдано:</label>
                <td>
                    <input type="text" name="lasttaker">
                </td>
            </div>
        </div>

search.php

<?php
if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['search'])) {
 require_once 'connect.php';
 $search = $_POST['search'];
 $limit = 10;
 $query = "SELECT *, CONCAT('../uploads/', file) as upload_file FROM infprintedit WHERE title LIKE '%$search%' LIMIT $limit";
 $result = mysqli_query($connect, $query);
 if (mysqli_num_rows($result) > 0) {
  while($row = mysqli_fetch_assoc($result)) {
   $title = $row['title'];
   $file = $row['file'];
   $author = $row['author'];
   $publicationtype = $row['publicationtype'];
   $place = $row['place'];
   $year = $row['year'];
   $publisher = $row['publisher'];
   $compedit = $row['compedit'];
   $countpages = $row['countpages'];
   $archive = $row['archive'];
   $BBK = $row['BBK'];
   $inventnumber = $row['inventnumber'];
   $numbinstances = $row['numbinstances'];
   $lasttaker = $row['lasttaker'];
// добавляем атрибуты data-* с нужными данными
echo "<div class='title_item' data-file='$file'
data-author='$author' 
data-publicationtype='$publicationtype' 
data-place='$place' 
data-year='$year' 
data-publisher='$publisher' 
data-compedit='$compedit' 
data-countpages='$countpages' 
data-archive='$archive'  
data-BBK='$BBK' 
data-inventnumber='$inventnumber'
data-numbinstances='$numbinstances' 
data-lasttaker='$lasttaker'>$title</div>";
}
}
mysqli_close($connect);
}
?>

get_image.php

<?php 
require_once 'connect.php';
$file = $_POST['file'];
$file_path = $_SERVER['DOCUMENT_ROOT'] . '../uploads/' . $file;
$query = "SELECT data FROM infprintedit WHERE file = '$file'";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
    $row = mysqli_fetch_assoc($result);
    $data = base64_encode($row['data']); // преобразуем данные в строку base64
    echo json_encode(['data' => $data]); // возвращаем данные в формате json
}
mysqli_close($connect);
?> 

Ответы

Ответов пока нет.